Skip to main content

Database

Struct Database 

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

An embedded Kōra database instance.

Database is the primary entry point for the embedded API. It owns a multi-threaded ShardEngine and a DocEngine, exposing typed methods for key-value, list, hash, set, vector, and document operations.

All methods are safe to call from multiple threads simultaneously. Key-value operations route through per-shard channels and block the caller until the owning shard worker completes the command. Document operations are coordinated by a RwLock over the in-memory document engine.

§Examples

use kora_embedded::{Config, Database};
use std::sync::Arc;

let db = Arc::new(Database::open(Config { shard_count: 4, ..Config::default() }));
db.set("counter", b"0");
db.incr("counter").unwrap();
assert_eq!(db.get("counter"), Some(b"1".to_vec()));

Implementations§

Source§

impl Database

Source

pub fn open(config: Config) -> Self

Open a new database with the given configuration.

This spawns config.shard_count background worker threads that remain alive for the lifetime of the returned Database.

Source

pub fn engine(&self) -> &ShardEngine

Return a reference to the underlying ShardEngine.

Source

pub fn shared_engine(&self) -> Arc<ShardEngine>

Return a shared handle to the underlying ShardEngine.

Useful when integrating with components that need their own Arc clone, such as hybrid server mode or custom command dispatch layers.

Source

pub fn shared_doc_engine(&self) -> Arc<RwLock<DocEngine>>

Return a shared handle to the embedded DocEngine.

Callers are responsible for acquiring the inner RwLock appropriately.

Source

pub fn doc_create_collection( &self, collection: &str, config: DocCollectionConfig, ) -> Result<u16, DocError>

Create a document collection.

Source

pub fn doc_drop_collection(&self, collection: &str) -> bool

Drop a document collection and all documents in it.

Source

pub fn doc_collection_info(&self, collection: &str) -> Option<DocCollectionInfo>

Return collection metadata, or None if the collection does not exist.

Source

pub fn doc_dictionary_info( &self, collection: &str, ) -> Result<DocDictionaryInfo, DocError>

Return dictionary statistics for a collection.

Source

pub fn doc_storage_info( &self, collection: &str, ) -> Result<DocStorageInfo, DocError>

Return packed storage statistics for a collection.

Source

pub fn doc_set( &self, collection: &str, doc_id: &str, json: &Value, ) -> Result<DocSetResult, DocError>

Insert or replace one JSON document.

Source

pub fn doc_insert( &self, collection: &str, json: &Value, ) -> Result<DocInsertResult, DocError>

Insert a document with an auto-generated ID.

Returns the generated ID and insert metadata.

Source

pub fn doc_mset( &self, collection: &str, entries: &[(&str, &Value)], ) -> Result<Vec<DocSetResult>, DocError>

Insert or replace multiple JSON documents in one collection.

Source

pub fn doc_get( &self, collection: &str, doc_id: &str, projection: Option<&[&str]>, ) -> Result<Option<Value>, DocError>

Read one JSON document, optionally projecting a subset of fields.

projection accepts dot-separated paths (e.g. "address.city") to return only the requested fields. Pass None to return the full document.

Source

pub fn doc_mget( &self, collection: &str, doc_ids: &[&str], ) -> Result<Vec<Option<Value>>, DocError>

Read multiple JSON documents from a collection in one call.

Missing documents appear as None in the returned vector, preserving positional correspondence with doc_ids.

Source

pub fn doc_update( &self, collection: &str, doc_id: &str, mutations: &[DocUpdateMutation], ) -> Result<bool, DocError>

Apply one or more field-level mutations to an existing document.

Returns Ok(true) when the document existed and was rewritten, Ok(false) when the target document is missing.

Source

pub fn doc_del(&self, collection: &str, doc_id: &str) -> Result<bool, DocError>

Delete a document. Returns Ok(true) if the document existed.

Source

pub fn doc_exists( &self, collection: &str, doc_id: &str, ) -> Result<bool, DocError>

Check whether a document exists in a collection.

Source

pub fn doc_create_index( &self, collection: &str, field: &str, index_type: &str, ) -> Result<(), DocError>

Create a secondary index on a collection field.

Source

pub fn doc_drop_index( &self, collection: &str, field: &str, ) -> Result<(), DocError>

Drop a secondary index from a collection field.

Source

pub fn doc_indexes( &self, collection: &str, ) -> Result<Vec<(String, String)>, DocError>

List all secondary indexes for a collection.

Returns (field_path, index_type_name) pairs where index_type_name is one of "hash", "sorted", "array", or "unique".

Source

pub fn doc_find( &self, collection: &str, where_clause: &str, projection: Option<&[&str]>, limit: Option<usize>, offset: usize, order_by: Option<&str>, order_desc: bool, ) -> Result<Vec<Value>, DocError>

Find documents matching a WHERE clause with optional projection, limit, offset, and sorting.

Source

pub fn doc_count( &self, collection: &str, where_clause: &str, ) -> Result<u64, DocError>

Count documents matching a WHERE clause.

Source

pub fn get(&self, key: &str) -> Option<Vec<u8>>

Return the value stored at key, or None if the key does not exist.

Source

pub fn set(&self, key: &str, value: &[u8])

Store a key-value pair, overwriting any existing value.

Source

pub fn set_ex(&self, key: &str, value: &[u8], ttl: Duration)

Store a key-value pair that expires after ttl.

Source

pub fn del(&self, key: &str) -> bool

Delete a key. Returns true if the key existed.

Source

pub fn exists(&self, key: &str) -> bool

Check whether key exists in the store.

Source

pub fn incr(&self, key: &str) -> Result<i64, String>

Atomically increment a key’s integer value by 1, returning the new value.

Source

pub fn getset(&self, key: &str, value: &[u8]) -> Option<Vec<u8>>

Atomically set key to value and return the previous value, if any.

Source

pub fn append(&self, key: &str, value: &[u8]) -> i64

Append value to the string stored at key, returning the new byte length.

Source

pub fn strlen(&self, key: &str) -> i64

Get the length of the string value stored at key.

Source

pub fn decr(&self, key: &str) -> Result<i64, String>

Atomically decrement a key’s integer value by 1, returning the new value.

Source

pub fn incrby(&self, key: &str, delta: i64) -> Result<i64, String>

Atomically increment a key’s integer value by delta, returning the new value.

Source

pub fn decrby(&self, key: &str, delta: i64) -> Result<i64, String>

Atomically decrement a key’s integer value by delta, returning the new value.

Source

pub fn mget(&self, keys: &[&str]) -> Vec<Option<Vec<u8>>>

Return the values of multiple keys in a single call.

Missing keys appear as None, preserving positional correspondence with keys.

Source

pub fn mset(&self, entries: &[(&str, &[u8])])

Store multiple key-value pairs in a single call.

Source

pub fn setnx(&self, key: &str, value: &[u8]) -> bool

Store a key-value pair only if the key does not already exist.

Returns true if the key was set, false if it already existed.

Source

pub fn expire(&self, key: &str, seconds: u64) -> bool

Set a time-to-live on key. Returns true if the key exists.

Source

pub fn persist(&self, key: &str) -> bool

Remove the time-to-live on key, making it persistent.

Returns true if the key existed and had a TTL.

Source

pub fn ttl(&self, key: &str) -> Option<i64>

Return the remaining time-to-live (in seconds) for key.

Returns None if the key does not exist or has no TTL set.

Source

pub fn key_type(&self, key: &str) -> String

Return the data type of the value stored at key (e.g. "string", "list", "none").

Source

pub fn keys(&self, pattern: &str) -> Vec<Vec<u8>>

Find all keys matching a glob pattern.

Source

pub fn lpush(&self, key: &str, values: &[&[u8]]) -> i64

Prepend one or more values to a list, returning the new length.

Source

pub fn rpush(&self, key: &str, values: &[&[u8]]) -> i64

Append one or more values to a list, returning the new length.

Source

pub fn lrange(&self, key: &str, start: i64, stop: i64) -> Vec<Vec<u8>>

Return a contiguous range of elements from a list.

Negative indices count from the end (-1 is the last element).

Source

pub fn lpop(&self, key: &str) -> Option<Vec<u8>>

Remove and return the first element of a list.

Source

pub fn rpop(&self, key: &str) -> Option<Vec<u8>>

Remove and return the last element of a list.

Source

pub fn llen(&self, key: &str) -> i64

Return the number of elements in a list.

Source

pub fn lindex(&self, key: &str, index: i64) -> Option<Vec<u8>>

Return the element at index in a list, or None if out of range.

Source

pub fn hset(&self, key: &str, field: &str, value: &[u8])

Set a field in a hash, creating the hash if it does not exist.

Source

pub fn hget(&self, key: &str, field: &str) -> Option<Vec<u8>>

Return the value of a hash field, or None if the field or hash does not exist.

Source

pub fn hdel(&self, key: &str, fields: &[&str]) -> i64

Remove one or more fields from a hash, returning the number of fields removed.

Source

pub fn hgetall(&self, key: &str) -> Vec<(Vec<u8>, Vec<u8>)>

Return all field-value pairs from a hash.

Source

pub fn hlen(&self, key: &str) -> i64

Return the number of fields in a hash.

Source

pub fn hexists(&self, key: &str, field: &str) -> bool

Check whether a field exists in a hash.

Source

pub fn hincrby(&self, key: &str, field: &str, delta: i64) -> Result<i64, String>

Atomically increment a hash field’s integer value by delta, returning the new value.

Source

pub fn sadd(&self, key: &str, members: &[&[u8]]) -> i64

Add one or more members to a set, returning the number of new members added.

Source

pub fn smembers(&self, key: &str) -> Vec<Vec<u8>>

Return all members of a set.

Source

pub fn srem(&self, key: &str, members: &[&[u8]]) -> i64

Remove one or more members from a set, returning the number of members removed.

Source

pub fn sismember(&self, key: &str, member: &[u8]) -> bool

Check whether member belongs to the set stored at key.

Source

pub fn scard(&self, key: &str) -> i64

Return the number of members in a set.

Source

pub fn db_size(&self) -> i64

Return the total number of keys across all shards.

Source

pub fn flush_db(&self)

Remove all keys from every shard.

Source

pub fn vector_set( &self, index: &str, dim: usize, vector: &[f32], ) -> Result<u64, String>

Insert a vector into a named index, returning the vector ID.

Creates the index if it does not exist.

Search for the K nearest neighbors of a query vector.

Returns a list of (id, distance) pairs sorted by distance.

Source

pub fn vector_del(&self, index: &str) -> Result<bool, String>

Delete an entire vector index. Returns true if it existed.

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