Skip to main content

Database

Struct Database 

Source
pub struct Database { /* private fields */ }
Expand description

Database instance managing collections and storage.

§Lifecycle

Database::open() automatically loads all previously created collections from disk. There is no need to call load_collections() separately.

§Extension (Premium)

Use Database::open_with_observer to inject a DatabaseObserver implementation from velesdb-premium without modifying this crate.

Implementations§

Source§

impl Database

Source

pub fn open<P: AsRef<Path>>(path: P) -> Result<Self>

Opens or creates a database, automatically loading all existing collections.

This replaces the previous open() + load_collections() two-step pattern. The new open() is a strict auto-load: all config.json directories under path are loaded on startup.

§Errors

Returns an error if the directory cannot be created or accessed.

Source

pub fn open_with_observer<P: AsRef<Path>>( path: P, observer: Arc<dyn DatabaseObserver>, ) -> Result<Self>

Opens a database with a DatabaseObserver (used by velesdb-premium).

The observer receives lifecycle hooks for every collection operation, enabling RBAC, audit logging, multi-tenant routing, etc.

§Errors

Returns an error if the directory cannot be created or accessed.

Source

pub fn create_collection( &self, name: &str, dimension: usize, metric: DistanceMetric, ) -> Result<()>

Creates a new collection with the specified parameters.

§Arguments
  • name - Unique name for the collection
  • dimension - Vector dimension (e.g., 768 for many embedding models)
  • metric - Distance metric to use for similarity calculations
§Errors

Returns an error if a collection with the same name already exists.

Source

pub fn create_collection_with_options( &self, name: &str, dimension: usize, metric: DistanceMetric, storage_mode: StorageMode, ) -> Result<()>

Creates a new collection with custom storage options.

§Arguments
  • name - Unique name for the collection
  • dimension - Vector dimension
  • metric - Distance metric
  • storage_mode - Vector storage mode (Full, SQ8, Binary)
§Errors

Returns an error if a collection with the same name already exists.

Source

pub fn data_dir(&self) -> &Path

Returns the path to the data directory.

Source

pub fn schema_version(&self) -> u64

Returns the current DDL schema version counter.

Source

pub fn plan_cache(&self) -> &CompiledPlanCache

Returns a reference to the compiled query plan cache.

Source

pub fn collection_write_generation(&self, name: &str) -> Option<u64>

Returns the write generation for a named collection, if it exists.

Checks the legacy registry first (covers all collection types).

Source

pub fn get_collection(&self, name: &str) -> Option<Collection>

Gets a reference to a collection by name.

§Arguments
  • name - Name of the collection
§Returns

Returns None if the collection does not exist.

Source

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

Analyzes a collection, caches stats, and persists them to disk.

§Errors

Returns an error if the collection does not exist, analysis fails, or stats cannot be serialized and written to disk.

Source

pub fn get_collection_stats( &self, name: &str, ) -> Result<Option<CollectionStats>>

Returns cached statistics when available, loading from disk if present.

§Errors

Returns an error if the on-disk stats file exists but cannot be read or deserialized.

Source

pub fn build_plan_key(&self, query: &Query) -> PlanKey

Builds a deterministic cache key for a query (CACHE-02).

Serialises the query to canonical JSON (object keys sorted recursively), reads the current schema_version, and gathers per-collection write_generation counters (sorted by collection name) to form a PlanKey.

§Why canonical JSON instead of Debug

format!("{query:?}") is non-deterministic when the Query AST contains HashMap-backed fields (FusionConfig::params, TrainStatement::params) because HashMap iteration order is not guaranteed across invocations. Canonical JSON with sorted object keys is stable and produces the same byte sequence for logically identical queries.

Source

pub fn explain_query(&self, query: &Query) -> Result<QueryPlan>

Returns the query plan for a query, with cache status populated (CACHE-02).

If the plan is cached, returns it with cache_hit: Some(true) and plan_reuse_count set. Otherwise generates a fresh plan with cache_hit: Some(false).

§Design decision: explain_query does not populate the cache

explain_query intentionally does not insert a new plan into the compiled plan cache. EXPLAIN is a diagnostic operation; allowing it to influence cache state would make cache metrics (hit/miss ratios, plan_reuse_count) unreliable because EXPLAIN calls would be indistinguishable from real execution hits. Only execute_query is authorised to write to the cache.

§Errors

Returns an error if the query is invalid.

Source

pub fn execute_query( &self, query: &Query, params: &HashMap<String, Value>, ) -> Result<Vec<SearchResult>>

Executes a VelesQL query with database-level JOIN resolution.

This method resolves JOIN target collections from the database registry and executes JOIN runtime in sequence. Query plans are cached and reused for identical queries against unchanged collections (CACHE-02).

§Errors

Returns an error if the base collection or any JOIN collection is missing.

Source

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

Lists all collection names in the database.

Includes collections created via any typed API (vector, graph, metadata).

Source

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

Deletes a collection by name.

§Arguments
  • name - Name of the collection to delete
§Errors

Returns an error if the collection does not exist in any registry.

§Concurrency

The existence check and the registry removals are not a single atomic operation. Under concurrent deletion of the same collection, at most one caller receives CollectionNotFound; subsequent callers perform no-op remove() calls which are safe and idempotent. remove_dir_all is guarded by an exists() check and is therefore also safe.

Source

pub fn create_vector_collection( &self, name: &str, dimension: usize, metric: DistanceMetric, ) -> Result<()>

Creates a new vector collection.

§Errors

Returns an error if a collection with the same name already exists.

Source

pub fn create_vector_collection_with_options( &self, name: &str, dimension: usize, metric: DistanceMetric, storage_mode: StorageMode, ) -> Result<()>

Creates a new vector collection with custom storage options.

§Errors

Returns an error if a collection with the same name already exists.

Source

pub fn create_graph_collection( &self, name: &str, schema: GraphSchema, ) -> Result<()>

Creates a new graph collection.

§Errors

Returns an error if a collection with the same name already exists.

Source

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

Creates a new metadata-only collection.

§Errors

Returns an error if a collection with the same name already exists.

Source

pub fn notify_upsert(&self, collection: &str, point_count: usize)

Notifies the observer that points were upserted into a collection.

Caller contract: this method is NOT called automatically by Database internals. HTTP handlers and SDK bindings are responsible for calling it after a successful upsert, passing the number of points written. Forgetting to call it means the observer receives no upsert events for that operation.

No-op when no observer is registered.

Source

pub fn notify_query(&self, collection: &str, duration_us: u64)

Notifies the observer that a query was executed, with its duration.

Caller contract: this method is NOT called automatically by Database::execute_query. Callers must measure the wall-clock duration themselves (e.g. std::time::Instant::now() before the call) and invoke this method afterwards with the elapsed microseconds.

No-op when no observer is registered.

Source

pub fn get_vector_collection(&self, name: &str) -> Option<VectorCollection>

Returns a VectorCollection by name.

Checks the typed registry first. If not found there, falls back to opening the collection directory from disk (e.g. for collections created via the legacy create_collection API that were not registered in the typed registry). The opened instance is cached back into the registry so subsequent calls avoid the disk round-trip.

Returns None if the collection does not exist on disk.

Source

pub fn get_graph_collection(&self, name: &str) -> Option<GraphCollection>

Returns a GraphCollection by name.

Checks the typed registry first. Falls back to opening from disk if the collection was not registered in-memory (e.g. after a restart or when the collection was auto-created by a graph handler). The instance is cached into the registry so subsequent calls are free.

Returns None if the collection does not exist on disk.

Source

pub fn get_metadata_collection(&self, name: &str) -> Option<MetadataCollection>

Returns a MetadataCollection by name.

Checks the typed registry first. Falls back to opening from disk for collections created before the typed API existed or after a restart. The instance is cached to avoid repeated disk reads.

Returns None if the collection does not exist on disk.

Source

pub fn create_collection_typed( &self, name: &str, collection_type: &CollectionType, ) -> Result<()>

Creates a new collection with a specific type (Vector or MetadataOnly).

§Arguments
  • name - Unique name for the collection
  • collection_type - Type of collection to create
§Errors

Returns an error if a collection with the same name already exists.

§Examples
use velesdb_core::{Database, CollectionType, DistanceMetric, StorageMode};

let db = Database::open("./data")?;

// Create a metadata-only collection
db.create_collection_typed("products", CollectionType::MetadataOnly)?;

// Create a vector collection
db.create_collection_typed("embeddings", CollectionType::Vector {
    dimension: 768,
    metric: DistanceMetric::Cosine,
    storage_mode: StorageMode::Full,
})?;
Source

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

Loads existing collections from disk.

§Deprecation note

This method is called automatically by Database::open. There is no need to call it manually. It is kept public only for backward compatibility with code that relied on the old two-step pattern.

§Errors

Returns an error if collection directories cannot be read.

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> Paint for T
where T: ?Sized,

Source§

fn fg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the foreground set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like red() and green(), which have the same functionality but are pithier.

§Example

Set foreground color to white using fg():

use yansi::{Paint, Color};

painted.fg(Color::White);

Set foreground color to white using white().

use yansi::Paint;

painted.white();
Source§

fn primary(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Primary].

§Example
println!("{}", value.primary());
Source§

fn fixed(&self, color: u8) -> Painted<&T>

Returns self with the fg() set to [Color :: Fixed].

§Example
println!("{}", value.fixed(color));
Source§

fn rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the fg() set to [Color :: Rgb].

§Example
println!("{}", value.rgb(r, g, b));
Source§

fn black(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Black].

§Example
println!("{}", value.black());
Source§

fn red(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Red].

§Example
println!("{}", value.red());
Source§

fn green(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Green].

§Example
println!("{}", value.green());
Source§

fn yellow(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Yellow].

§Example
println!("{}", value.yellow());
Source§

fn blue(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Blue].

§Example
println!("{}", value.blue());
Source§

fn magenta(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Magenta].

§Example
println!("{}", value.magenta());
Source§

fn cyan(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Cyan].

§Example
println!("{}", value.cyan());
Source§

fn white(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: White].

§Example
println!("{}", value.white());
Source§

fn bright_black(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightBlack].

§Example
println!("{}", value.bright_black());
Source§

fn bright_red(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightRed].

§Example
println!("{}", value.bright_red());
Source§

fn bright_green(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightGreen].

§Example
println!("{}", value.bright_green());
Source§

fn bright_yellow(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightYellow].

§Example
println!("{}", value.bright_yellow());
Source§

fn bright_blue(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightBlue].

§Example
println!("{}", value.bright_blue());
Source§

fn bright_magenta(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightMagenta].

§Example
println!("{}", value.bright_magenta());
Source§

fn bright_cyan(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightCyan].

§Example
println!("{}", value.bright_cyan());
Source§

fn bright_white(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightWhite].

§Example
println!("{}", value.bright_white());
Source§

fn bg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the background set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like on_red() and on_green(), which have the same functionality but are pithier.

§Example

Set background color to red using fg():

use yansi::{Paint, Color};

painted.bg(Color::Red);

Set background color to red using on_red().

use yansi::Paint;

painted.on_red();
Source§

fn on_primary(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Primary].

§Example
println!("{}", value.on_primary());
Source§

fn on_fixed(&self, color: u8) -> Painted<&T>

Returns self with the bg() set to [Color :: Fixed].

§Example
println!("{}", value.on_fixed(color));
Source§

fn on_rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the bg() set to [Color :: Rgb].

§Example
println!("{}", value.on_rgb(r, g, b));
Source§

fn on_black(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Black].

§Example
println!("{}", value.on_black());
Source§

fn on_red(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Red].

§Example
println!("{}", value.on_red());
Source§

fn on_green(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Green].

§Example
println!("{}", value.on_green());
Source§

fn on_yellow(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Yellow].

§Example
println!("{}", value.on_yellow());
Source§

fn on_blue(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Blue].

§Example
println!("{}", value.on_blue());
Source§

fn on_magenta(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Magenta].

§Example
println!("{}", value.on_magenta());
Source§

fn on_cyan(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Cyan].

§Example
println!("{}", value.on_cyan());
Source§

fn on_white(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: White].

§Example
println!("{}", value.on_white());
Source§

fn on_bright_black(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightBlack].

§Example
println!("{}", value.on_bright_black());
Source§

fn on_bright_red(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightRed].

§Example
println!("{}", value.on_bright_red());
Source§

fn on_bright_green(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightGreen].

§Example
println!("{}", value.on_bright_green());
Source§

fn on_bright_yellow(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightYellow].

§Example
println!("{}", value.on_bright_yellow());
Source§

fn on_bright_blue(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightBlue].

§Example
println!("{}", value.on_bright_blue());
Source§

fn on_bright_magenta(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightMagenta].

§Example
println!("{}", value.on_bright_magenta());
Source§

fn on_bright_cyan(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightCyan].

§Example
println!("{}", value.on_bright_cyan());
Source§

fn on_bright_white(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightWhite].

§Example
println!("{}", value.on_bright_white());
Source§

fn attr(&self, value: Attribute) -> Painted<&T>

Enables the styling Attribute value.

This method should be used rarely. Instead, prefer to use attribute-specific builder methods like bold() and underline(), which have the same functionality but are pithier.

§Example

Make text bold using attr():

use yansi::{Paint, Attribute};

painted.attr(Attribute::Bold);

Make text bold using using bold().

use yansi::Paint;

painted.bold();
Source§

fn bold(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Bold].

§Example
println!("{}", value.bold());
Source§

fn dim(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Dim].

§Example
println!("{}", value.dim());
Source§

fn italic(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Italic].

§Example
println!("{}", value.italic());
Source§

fn underline(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Underline].

§Example
println!("{}", value.underline());

Returns self with the attr() set to [Attribute :: Blink].

§Example
println!("{}", value.blink());

Returns self with the attr() set to [Attribute :: RapidBlink].

§Example
println!("{}", value.rapid_blink());
Source§

fn invert(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Invert].

§Example
println!("{}", value.invert());
Source§

fn conceal(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Conceal].

§Example
println!("{}", value.conceal());
Source§

fn strike(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Strike].

§Example
println!("{}", value.strike());
Source§

fn quirk(&self, value: Quirk) -> Painted<&T>

Enables the yansi Quirk value.

This method should be used rarely. Instead, prefer to use quirk-specific builder methods like mask() and wrap(), which have the same functionality but are pithier.

§Example

Enable wrapping using .quirk():

use yansi::{Paint, Quirk};

painted.quirk(Quirk::Wrap);

Enable wrapping using wrap().

use yansi::Paint;

painted.wrap();
Source§

fn mask(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Mask].

§Example
println!("{}", value.mask());
Source§

fn wrap(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Wrap].

§Example
println!("{}", value.wrap());
Source§

fn linger(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Linger].

§Example
println!("{}", value.linger());
Source§

fn clear(&self) -> Painted<&T>

👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear(). The clear() method will be removed in a future release.

Returns self with the quirk() set to [Quirk :: Clear].

§Example
println!("{}", value.clear());
Source§

fn resetting(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Resetting].

§Example
println!("{}", value.resetting());
Source§

fn bright(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Bright].

§Example
println!("{}", value.bright());
Source§

fn on_bright(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: OnBright].

§Example
println!("{}", value.on_bright());
Source§

fn whenever(&self, value: Condition) -> Painted<&T>

Conditionally enable styling based on whether the Condition value applies. Replaces any previous condition.

See the crate level docs for more details.

§Example

Enable styling painted only when both stdout and stderr are TTYs:

use yansi::{Paint, Condition};

painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);
Source§

fn new(self) -> Painted<Self>
where Self: Sized,

Create a new Painted with a default Style. Read more
Source§

fn paint<S>(&self, style: S) -> Painted<&Self>
where S: Into<Style>,

Apply a style wholesale to self. Any previous style is replaced. 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, 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