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
impl EmbeddedDatabase
Sourcepub fn new_in_memory() -> Result<Self>
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()?;Sourcepub fn with_config(config: Config) -> Result<Self>
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)?;Sourcepub fn query_timeout_ms(&self) -> Option<u64>
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)
Sourcepub fn execute_batch(&self, statements: &[&str]) -> Result<u64>
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.
pub fn execute(&self, sql: &str) -> Result<u64>
Sourcepub fn execute_returning(&self, sql: &str) -> Result<(u64, Vec<Tuple>)>
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);Sourcepub fn execute_params(&self, sql: &str, params: &[Value]) -> Result<u64>
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.
Sourcepub fn execute_params_returning(
&self,
sql: &str,
params: &[Value],
) -> Result<(u64, Vec<Tuple>)>
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$Nparameter placeholdersparams- 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);Sourcepub fn query(&self, sql: &str, _params: &[&dyn Display]) -> Result<Vec<Tuple>>
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 queryparams- 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", &[])?;Sourcepub fn query_with_columns(&self, sql: &str) -> Result<(Vec<Tuple>, Vec<String>)>
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.
Sourcepub fn dump_full(&self, path: &Path) -> Result<DumpMetadata>
pub fn dump_full(&self, path: &Path) -> Result<DumpMetadata>
Sourcepub fn dump_sql(&self, path: &Path) -> Result<DumpMetadata>
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
Sourcepub fn dump_incremental(&self, path: &Path) -> Result<DumpMetadata>
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
Sourcepub fn dump_incremental_append(&self, path: &Path) -> Result<DumpMetadata>
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
Sourcepub fn restore_from_dump(&mut self, path: &Path) -> Result<()>
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
Sourcepub fn dump_full_compressed(
&self,
path: &Path,
compression: DumpCompressionType,
) -> Result<DumpMetadata>
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 writtencompression- Compression algorithm to use (None, Gzip, Zstd)
Sourcepub fn dump_full_uncompressed(&self, path: &Path) -> Result<DumpMetadata>
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
Sourcepub fn dump_tables(
&self,
path: &Path,
tables: Vec<&str>,
) -> Result<DumpMetadata>
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 writtentables- List of table names to include in the dump
Sourcepub fn restore_tables(&mut self, path: &Path, _tables: Vec<&str>) -> Result<()>
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
Sourcepub fn read_dump_metadata(&self, path: &Path) -> Result<DumpMetadata>
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
Sourcepub fn create_session(
&self,
user_name: &str,
isolation: IsolationLevel,
) -> Result<SessionId>
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 sessionisolation- 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)?;Sourcepub fn destroy_session(&self, session_id: SessionId) -> Result<()>
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
Sourcepub fn begin_transaction_for_session(&self, session_id: SessionId) -> Result<()>
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.
Sourcepub fn commit_transaction_for_session(
&self,
session_id: SessionId,
) -> Result<()>
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.
Sourcepub fn rollback_transaction_for_session(
&self,
session_id: SessionId,
) -> Result<()>
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.
Sourcepub fn execute_in_session(
&self,
session_id: SessionId,
sql: &str,
) -> Result<u64>
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 insql- SQL statement to execute
§Returns
Number of rows affected by the statement
Sourcepub fn query_in_session(
&self,
session_id: SessionId,
sql: &str,
_params: &[&dyn Display],
) -> Result<Vec<Tuple>>
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 insql- SQL SELECT query_params- Query parameters (reserved for future use)
§Returns
Vector of tuples matching the query
Sourcepub fn set_session_quota(
&self,
_user_name: &str,
_max_sessions: usize,
) -> Result<()>
pub fn set_session_quota( &self, _user_name: &str, _max_sessions: usize, ) -> Result<()>
Set session quota for a user
Sourcepub fn set_memory_quota(
&self,
_user_name: &str,
_max_bytes: usize,
) -> Result<()>
pub fn set_memory_quota( &self, _user_name: &str, _max_bytes: usize, ) -> Result<()>
Set memory quota for a user
Sourcepub fn mark_table_dirty(&self, table: &str)
pub fn mark_table_dirty(&self, table: &str)
Mark a table as dirty (for testing)
Sourcepub fn query_params(&self, sql: &str, params: &[Value]) -> Result<Vec<Tuple>>
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.
Sourcepub fn begin(&self) -> Result<()>
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.
Sourcepub fn commit(&self) -> Result<()>
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.
Sourcepub fn rollback(&self) -> Result<()>
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.
Sourcepub fn in_transaction(&self) -> bool
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());Sourcepub fn begin_transaction(&self) -> Result<Transaction<'_>>
👎Deprecated since 2.1.0: Use begin(), commit(), and rollback() instead
pub fn begin_transaction(&self) -> Result<Transaction<'_>>
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()?;Sourcepub fn current_lsn(&self) -> Option<u64>
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.
Sourcepub fn close(self) -> Result<()>
pub fn close(self) -> Result<()>
Close the database
Flushes pending data and releases resources. The database will also be cleaned up automatically when dropped.
Sourcepub fn list_vector_stores(&self) -> Result<Vec<VectorStoreInfo>>
pub fn list_vector_stores(&self) -> Result<Vec<VectorStoreInfo>>
List all vector stores
Sourcepub fn create_vector_store(
&self,
name: &str,
dimensions: u32,
) -> Result<VectorStoreInfo>
pub fn create_vector_store( &self, name: &str, dimensions: u32, ) -> Result<VectorStoreInfo>
Create a new vector store
Sourcepub fn get_vector_store(&self, name: &str) -> Result<VectorStoreInfo>
pub fn get_vector_store(&self, name: &str) -> Result<VectorStoreInfo>
Get vector store info
Sourcepub fn delete_vector_store(&self, name: &str) -> Result<()>
pub fn delete_vector_store(&self, name: &str) -> Result<()>
Delete a vector store
Sourcepub fn insert_vectors(
&self,
store: &str,
vectors: Vec<Vec<f32>>,
) -> Result<Vec<String>>
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
Sourcepub fn upsert_vectors(
&self,
store: &str,
vectors: Vec<(String, Vec<f32>)>,
) -> Result<()>
pub fn upsert_vectors( &self, store: &str, vectors: Vec<(String, Vec<f32>)>, ) -> Result<()>
Upsert vectors (insert or update)
Sourcepub fn search_vectors(
&self,
store: &str,
query: Vec<f32>,
k: usize,
) -> Result<Vec<(String, f32)>>
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
Sourcepub fn text_search(&self, _query: &str) -> Result<Vec<String>>
pub fn text_search(&self, _query: &str) -> Result<Vec<String>>
Text search (requires text embedding - stub for now)
Sourcepub fn store_texts(
&self,
_store: &str,
_texts: Vec<String>,
) -> Result<Vec<String>>
pub fn store_texts( &self, _store: &str, _texts: Vec<String>, ) -> Result<Vec<String>>
Store texts for embedding (requires embedding model - stub for now)
Sourcepub fn hybrid_search(
&self,
_store: &str,
_query: &str,
_k: usize,
) -> Result<Vec<(String, f32)>>
pub fn hybrid_search( &self, _store: &str, _query: &str, _k: usize, ) -> Result<Vec<(String, f32)>>
Hybrid search (vector + text) - requires embedding model
Sourcepub fn fetch_vectors(
&self,
_store: &str,
_ids: Vec<String>,
) -> Result<Vec<(String, Vec<f32>)>>
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)
Sourcepub fn list_agent_sessions(&self) -> Result<Vec<AgentSession>>
pub fn list_agent_sessions(&self) -> Result<Vec<AgentSession>>
List agent sessions
Sourcepub fn create_agent_session(&self, _name: &str) -> Result<AgentSession>
pub fn create_agent_session(&self, _name: &str) -> Result<AgentSession>
Create agent session
Sourcepub fn get_agent_session(&self, _id: &str) -> Result<AgentSession>
pub fn get_agent_session(&self, _id: &str) -> Result<AgentSession>
Get agent session
Sourcepub fn delete_agent_session(&self, _id: &str) -> Result<()>
pub fn delete_agent_session(&self, _id: &str) -> Result<()>
Delete agent session
Sourcepub fn add_agent_message(
&self,
_session_id: &str,
_role: &str,
_content: &str,
) -> Result<AgentMessage>
pub fn add_agent_message( &self, _session_id: &str, _role: &str, _content: &str, ) -> Result<AgentMessage>
Add message to agent session
Sourcepub fn get_agent_messages(&self, _session_id: &str) -> Result<Vec<AgentMessage>>
pub fn get_agent_messages(&self, _session_id: &str) -> Result<Vec<AgentMessage>>
Get messages from agent session
Sourcepub fn clear_agent_messages(&self, _session_id: &str) -> Result<()>
pub fn clear_agent_messages(&self, _session_id: &str) -> Result<()>
Clear agent session messages
Sourcepub fn generate_schema(&self, _table_name: &str) -> Result<String>
pub fn generate_schema(&self, _table_name: &str) -> Result<String>
Generate schema from data
Sourcepub fn chat_completion(
&self,
_messages: Vec<(String, String)>,
) -> Result<String>
pub fn chat_completion( &self, _messages: Vec<(String, String)>, ) -> Result<String>
Get AI chat completion
Sourcepub fn store_document(
&self,
_collection: &str,
_id: &str,
_content: &str,
_metadata: Option<Value>,
) -> Result<()>
pub fn store_document( &self, _collection: &str, _id: &str, _content: &str, _metadata: Option<Value>, ) -> Result<()>
Store document
Sourcepub fn get_document(&self, _collection: &str, _id: &str) -> Result<DocumentData>
pub fn get_document(&self, _collection: &str, _id: &str) -> Result<DocumentData>
Get document
Sourcepub fn update_document(
&self,
_collection: &str,
_id: &str,
_content: &str,
_metadata: Option<Value>,
) -> Result<()>
pub fn update_document( &self, _collection: &str, _id: &str, _content: &str, _metadata: Option<Value>, ) -> Result<()>
Update document
Sourcepub fn list_documents(&self, _collection: &str) -> Result<Vec<DocumentMetadata>>
pub fn list_documents(&self, _collection: &str) -> Result<Vec<DocumentMetadata>>
List documents in collection
Sourcepub fn search_documents(
&self,
_collection: &str,
_query: &str,
) -> Result<Vec<DocumentData>>
pub fn search_documents( &self, _collection: &str, _query: &str, ) -> Result<Vec<DocumentData>>
Search documents
Sourcepub fn create_collection(&self, _name: &str) -> Result<()>
pub fn create_collection(&self, _name: &str) -> Result<()>
Create collection
Sourcepub fn delete_collection(&self, _name: &str) -> Result<()>
pub fn delete_collection(&self, _name: &str) -> Result<()>
Delete collection
Sourcepub fn list_collections(&self) -> Result<Vec<String>>
pub fn list_collections(&self) -> Result<Vec<String>>
List collections
Sourcepub fn batch_create_documents(
&self,
_collection: &str,
_docs: Vec<DocumentData>,
) -> Result<Vec<String>>
pub fn batch_create_documents( &self, _collection: &str, _docs: Vec<DocumentData>, ) -> Result<Vec<String>>
Batch create documents
Sourcepub fn chat_completion_stream(
&self,
_messages: Vec<(String, String)>,
) -> Result<String>
pub fn chat_completion_stream( &self, _messages: Vec<(String, String)>, ) -> Result<String>
Chat completion stream
Sourcepub fn compare_schemas(
&self,
_schema1: &Schema,
_schema2: &Schema,
) -> Result<Value>
pub fn compare_schemas( &self, _schema1: &Schema, _schema2: &Schema, ) -> Result<Value>
Compare schemas
Sourcepub fn create_embeddings(&self, _texts: Vec<String>) -> Result<Vec<Vec<f32>>>
pub fn create_embeddings(&self, _texts: Vec<String>) -> Result<Vec<Vec<f32>>>
Create embeddings
Sourcepub fn create_document(
&self,
_collection: &str,
_id: &str,
_content: &str,
_metadata: Option<Value>,
) -> Result<String>
pub fn create_document( &self, _collection: &str, _id: &str, _content: &str, _metadata: Option<Value>, ) -> Result<String>
Create document (alias for store_document)
Sourcepub fn find_similar_documents(
&self,
_collection: &str,
_query: &str,
_limit: usize,
) -> Result<Vec<(DocumentData, f32)>>
pub fn find_similar_documents( &self, _collection: &str, _query: &str, _limit: usize, ) -> Result<Vec<(DocumentData, f32)>>
Find similar documents
Sourcepub fn fork_agent_session(
&self,
_session_id: &str,
_new_name: &str,
) -> Result<AgentSession>
pub fn fork_agent_session( &self, _session_id: &str, _new_name: &str, ) -> Result<AgentSession>
Fork agent session
Sourcepub fn generate_schema_from_description(
&self,
_description: &str,
) -> Result<Schema>
pub fn generate_schema_from_description( &self, _description: &str, ) -> Result<Schema>
Generate schema from description
Sourcepub fn get_agent_context(&self, _session_id: &str) -> Result<Value>
pub fn get_agent_context(&self, _session_id: &str) -> Result<Value>
Get agent context
Sourcepub fn get_chat_model(&self, _model_id: &str) -> Result<Value>
pub fn get_chat_model(&self, _model_id: &str) -> Result<Value>
Get chat model
Sourcepub fn get_document_chunks(
&self,
_collection: &str,
_id: &str,
) -> Result<Vec<(String, f32)>>
pub fn get_document_chunks( &self, _collection: &str, _id: &str, ) -> Result<Vec<(String, f32)>>
Get document chunks
Sourcepub fn infer_schema_from_file(&self, _path: &str) -> Result<Schema>
pub fn infer_schema_from_file(&self, _path: &str) -> Result<Schema>
Infer schema from file
Sourcepub fn instantiate_schema_template(
&self,
_template_name: &str,
_params: Value,
) -> Result<Schema>
pub fn instantiate_schema_template( &self, _template_name: &str, _params: Value, ) -> Result<Schema>
Instantiate schema template
Sourcepub fn list_chat_models(&self) -> Result<Vec<Value>>
pub fn list_chat_models(&self) -> Result<Vec<Value>>
List chat models
Sourcepub fn list_schema_templates(&self) -> Result<Vec<Value>>
pub fn list_schema_templates(&self) -> Result<Vec<Value>>
List schema templates
Sourcepub fn optimize_schema(&self, _schema: &Schema) -> Result<Schema>
pub fn optimize_schema(&self, _schema: &Schema) -> Result<Schema>
Optimize schema
Sourcepub fn validate_schema(&self, _schema: &Schema) -> Result<bool>
pub fn validate_schema(&self, _schema: &Schema) -> Result<bool>
Validate schema
Sourcepub fn rag_search(
&self,
_collection: &str,
_query: &str,
_k: usize,
) -> Result<Vec<(DocumentData, f32, String)>>
pub fn rag_search( &self, _collection: &str, _query: &str, _k: usize, ) -> Result<Vec<(DocumentData, f32, String)>>
RAG search (Retrieval Augmented Generation)
Sourcepub fn rechunk_document(
&self,
_collection: &str,
_id: &str,
_chunk_size: usize,
) -> Result<Vec<String>>
pub fn rechunk_document( &self, _collection: &str, _id: &str, _chunk_size: usize, ) -> Result<Vec<String>>
Rechunk document
Sourcepub fn search_agent_memory(
&self,
_session_id: &str,
_query: &str,
) -> Result<Vec<(AgentMessage, f32)>>
pub fn search_agent_memory( &self, _session_id: &str, _query: &str, ) -> Result<Vec<(AgentMessage, f32)>>
Search agent memory
Sourcepub fn summarize_agent_memory(&self, _session_id: &str) -> Result<String>
pub fn summarize_agent_memory(&self, _session_id: &str) -> Result<String>
Summarize agent memory
Sourcepub fn create_branch(&self, name: &str) -> Result<u64>
pub fn create_branch(&self, name: &str) -> Result<u64>
Create an isolated database branch (copy-on-write).
Sourcepub fn switch_branch(&self, name: &str) -> Result<u64>
pub fn switch_branch(&self, name: &str) -> Result<u64>
Switch the active branch.
Sourcepub fn merge_branch(&self, source: &str) -> Result<u64>
pub fn merge_branch(&self, source: &str) -> Result<u64>
Merge a branch into the current branch.
Sourcepub fn drop_branch(&self, name: &str) -> Result<u64>
pub fn drop_branch(&self, name: &str) -> Result<u64>
Drop a branch.
Sourcepub fn list_branches(&self) -> Result<Vec<Tuple>>
pub fn list_branches(&self) -> Result<Vec<Tuple>>
List all branches.
Sourcepub fn explain(&self, sql: &str) -> Result<Vec<Tuple>>
pub fn explain(&self, sql: &str) -> Result<Vec<Tuple>>
Return the query execution plan as a string.
Sourcepub fn explain_analyze(&self, sql: &str) -> Result<Vec<Tuple>>
pub fn explain_analyze(&self, sql: &str) -> Result<Vec<Tuple>>
Return the query execution plan with runtime statistics.
Sourcepub fn refresh_materialized_view(&self, name: &str) -> Result<u64>
pub fn refresh_materialized_view(&self, name: &str) -> Result<u64>
Refresh a materialized view.
Sourcepub fn reset_all_qps_windows(&self)
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();Sourcepub fn database_name_is_valid(&self, name: &str) -> bool
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.
Sourcepub async fn start_auto_refresh(
&self,
config: Option<AutoRefreshConfig>,
) -> Result<()>
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(())
}Sourcepub async fn stop_auto_refresh(&self) -> Result<()>
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.
Sourcepub fn is_auto_refresh_running(&self) -> bool
pub fn is_auto_refresh_running(&self) -> bool
Check if the auto-refresh worker is currently running
Sourcepub fn mv_scheduler(&self) -> &Arc<MVScheduler>
pub fn mv_scheduler(&self) -> &Arc<MVScheduler>
Get the MV scheduler for manual scheduling operations
Sourcepub fn check_mv_staleness_now(&self) -> Result<()>
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
impl DatabaseInterface for EmbeddedDatabase
Source§fn get_table_indexes(&self, table: &str) -> Result<Vec<IndexMetadata>>
fn get_table_indexes(&self, table: &str) -> Result<Vec<IndexMetadata>>
Auto Trait Implementations§
impl Freeze for EmbeddedDatabase
impl !RefUnwindSafe for EmbeddedDatabase
impl Send for EmbeddedDatabase
impl Sync for EmbeddedDatabase
impl Unpin for EmbeddedDatabase
impl UnsafeUnpin for EmbeddedDatabase
impl !UnwindSafe for EmbeddedDatabase
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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