Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
graphdblite
https://docs.rs/graphdblite/0.1.2/graphdblite/
Admin
graphdblite is an embedded graph database with a Cypher query interface backed by SQLite.
Tokens:
16,481
Snippets:
186
Trust Score:
9.1
Update:
1 month ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### HashMap IntoIterator example Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Example usage of IntoIterator for HashMap. ```rust use std::collections::HashMap; ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Examples of copying or cloning the contents of an Ok variant from a reference. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Get Value from HashMap Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Retrieves a reference to the value associated with a given key. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Chain fallible operations with and_then Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Use and_then to chain operations that return a Result. The provided examples demonstrate handling successful results, overflow errors, and existing error states. ```rust assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Get HashMap Hasher Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Retrieves a reference to the map's BuildHasher. ```rust use std::collections::HashMap; use std::hash::RandomState; let hasher = RandomState::new(); let map: HashMap<i32, i32> = HashMap::with_hasher(hasher); let hasher: &RandomState = map.hasher(); ``` -------------------------------- ### Initialize and Query Database Source: https://docs.rs/graphdblite Demonstrates opening an in-memory database, executing a Cypher creation statement, and performing a retrieval query. ```rust use graphdblite::Database; let mut db = Database::open_memory().unwrap(); db.execute("CREATE (:Person {name: 'Alice'})").unwrap(); let rows = db.execute("MATCH (p:Person) RETURN p.name AS name").unwrap(); assert_eq!(rows.len(), 1); ``` -------------------------------- ### Database Initialization Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Methods to open or create a new database instance. ```APIDOC ## Database::open ### Description Opens a database at the given file path. ## Database::open_with_config ### Description Opens a database with custom configuration. ## Database::open_memory ### Description Opens an in-memory database for testing purposes. ``` -------------------------------- ### Initialize HashMap Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Standard methods for creating new HashMap instances. ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::new(); ``` ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::with_capacity(10); ``` -------------------------------- ### Initialize HashMap with Allocator Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Experimental methods for creating HashMaps with custom allocators. ```rust use std::collections::HashMap; use std::alloc::Global; let map: HashMap<i32, i32> = HashMap::new_in(Global); ``` ```rust use std::collections::HashMap; use std::alloc::Global; let map: HashMap<i32, i32> = HashMap::with_capacity_in(10, Global); ``` -------------------------------- ### Get mutable reference to value Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Retrieve a mutable reference to a value associated with a key. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); ``` -------------------------------- ### Initialize HashMap with custom hasher and allocator Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Creates an empty HashMap using a specific hash builder and allocator. Requires the nightly-only allocator_api feature. ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap<i32, i32> = HashMap::with_hasher_in(s, Global); ``` ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap<i32, i32> = HashMap::with_capacity_and_hasher_in(10, s, Global); ``` -------------------------------- ### Initialize HashMap with Hasher Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Methods for creating HashMaps using custom hash builders. ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_hasher(s); map.insert(1, 2); ``` ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); ``` -------------------------------- ### Create HashMap from array Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Shows how to initialize a HashMap from an array of tuples using From or into(). ```rust use std::collections::HashMap; let map1 = HashMap::from([(1, 2), (3, 4)]); let map2: HashMap<_, _> = [(1, 2), (3, 4)].into(); assert_eq!(map1, map2); ``` -------------------------------- ### snapshot_to Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Writes a consistent snapshot of the database to a file. ```APIDOC ## pub fn snapshot_to<P: AsRef<Path>>(&mut self, path: P) -> Result<()> ### Description Writes a consistent snapshot of the database to the specified `path` as a single self-contained SQLite file. This operation uses `VACUUM INTO` and requires that no transaction is active on the handle. ``` -------------------------------- ### pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> HashMap<K, V, S, A> Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Creates an empty HashMap with at least the specified capacity, using a custom hasher and allocator. ```APIDOC ## pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> HashMap<K, V, S, A> ### Description Creates an empty `HashMap` with at least the specified capacity, using `hasher` to hash the keys and `alloc` to allocate memory. ### Parameters - **capacity** (usize) - Required - The initial capacity of the map. - **hash_builder** (S) - Required - The hash builder to use. - **alloc** (A) - Required - The allocator to use. ``` -------------------------------- ### Database::open_memory Source: https://docs.rs/graphdblite Opens an in-memory graph database instance. ```APIDOC ## Database::open_memory ### Description Creates and opens a new graph database instance in memory. ### Signature `pub fn open_memory() -> Result<Database, GraphError>` ### Returns - **Database** - The initialized database instance. - **GraphError** - Error if the database could not be opened. ``` -------------------------------- ### create_fulltext_index_word_multi Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Creates a multi-property word-tokenized fulltext index on a label. ```APIDOC ## pub fn create_fulltext_index_word_multi(&mut self, label: &str, properties: &[String]) -> Result<()> ### Description Creates a multi-property word-tokenized fulltext index on `label`. One FTS5 virtual table covers all listed properties, allowing for cross-column searches via `fts.search`. ``` -------------------------------- ### pub fn keys(&self) -> Keys<'_, K, V> Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Returns an iterator visiting all keys in arbitrary order. ```APIDOC ## pub fn keys(&self) -> Keys<'_, K, V> ### Description An iterator visiting all keys in arbitrary order. The iterator element type is `&'a K`. ``` -------------------------------- ### Try insert key-value pair Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Experimental API to insert a value only if the key is not already present. ```rust #![feature(map_try_insert)] use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.try_insert(37, "a").unwrap(), &"a"); let err = map.try_insert(37, "b").unwrap_err(); assert_eq!(err.entry.key(), &37); assert_eq!(err.entry.get(), &"a"); assert_eq!(err.key, 37); assert_eq!(err.value, "b"); ``` -------------------------------- ### pub fn into_keys(self) -> IntoKeys<K, V, A> Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Creates a consuming iterator visiting all the keys in arbitrary order. ```APIDOC ## pub fn into_keys(self) -> IntoKeys<K, V, A> ### Description Creates a consuming iterator visiting all the keys in arbitrary order. The map cannot be used after calling this. ``` -------------------------------- ### pub fn with_hasher_in(hash_builder: S, alloc: A) -> HashMap<K, V, S, A> Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Creates an empty HashMap which will use the given hash builder and allocator. ```APIDOC ## pub fn with_hasher_in(hash_builder: S, alloc: A) -> HashMap<K, V, S, A> ### Description Creates an empty `HashMap` which will use the given hash builder and allocator. The created map has the default initial capacity. ### Parameters - **hash_builder** (S) - Required - The hash builder to use for the map. - **alloc** (A) - Required - The allocator to use for memory management. ``` -------------------------------- ### Index Management Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Methods for creating and dropping indexes on labels and properties. ```APIDOC ## Database::create_index ### Description Creates a secondary index on (label, property) inside an active write transaction. ## Database::drop_index ### Description Drops a secondary index on (label, property) inside an active write transaction. ## Database::create_composite_index ### Description Creates a composite index on (label, properties) inside an active write transaction. ## Database::drop_composite_index ### Description Drops a composite index on (label, properties) inside an active write transaction. ``` -------------------------------- ### Config Struct Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Config.html The primary configuration structure for opening a database, containing various tuning parameters for performance and safety. ```rust pub struct Config { pub busy_timeout_ms: u32, pub synchronous: SyncMode, pub max_traversal_depth: u32, pub max_traversal_work: u64, pub max_property_value_bytes: usize, pub max_name_bytes: usize, pub max_result_rows: usize, pub cache_size: i32, pub mmap_size: i64, } ``` -------------------------------- ### And Chaining Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the provided result if the current result is Ok, otherwise returns the Err. ```rust let x: Result<u32, &str> = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result<u32, &str> = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result<u32, &str> = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result<u32, &str> = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### HashMap remove_entry and remove usage Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Demonstrates removing entries from a HashMap and handling the return values. ```rust let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove_entry(&1), Some((1, "a"))); assert_eq!(map.remove(&1), None); ``` -------------------------------- ### Unwrap with Default Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the Ok value or a default value if the result is Err. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### create_fulltext_index_word Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Creates a word-tokenized fulltext index using the unicode61 tokenizer. ```APIDOC ## pub fn create_fulltext_index_word(&mut self, label: &str, property: &str) -> Result<()> ### Description Creates a word-tokenized fulltext index on `(label, property)` backed by FTS5's `unicode61` tokenizer. This is suitable for use with the `fts.search` procedure. ``` -------------------------------- ### Try Reserve HashMap Capacity Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Attempts to reserve capacity, returning an error if the allocation fails or overflows. ```rust use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::new(); map.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?"); ``` -------------------------------- ### Database::execute Source: https://docs.rs/graphdblite Executes a Cypher query against the database. ```APIDOC ## Database::execute ### Description Executes a provided Cypher query string and returns the resulting records. ### Signature `pub fn execute(&mut self, query: &str) -> Result<Vec<Record>, GraphError>` ### Parameters - **query** (&str) - The Cypher query string to execute. ### Returns - **Vec<Record>** - A collection of result records. - **GraphError** - Error if the query execution fails. ``` -------------------------------- ### Provide default value with unwrap_or Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the contained Ok value or a provided default value. Arguments are eagerly evaluated. ```rust let default = 2; let x: Result<u32, &str> = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result<u32, &str> = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Iterate over HashMap keys Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Provides an iterator over keys in arbitrary order. Note that iteration performance is O(capacity). ```rust use std::collections::HashMap; let map: HashMap<&str, i32> = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut values: Vec<_> = map.keys().copied().collect(); values.sort(); assert_eq!(values, vec!["a", "b", "c"]); ``` -------------------------------- ### Collect Result Iterator Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Demonstrates how collecting an iterator of Results short-circuits on the first Err encountered. ```rust let v = vec![1, 2]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### HashMap Serialization Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Provides the serialization method for HashMap using the Serde framework, requiring the std feature. ```rust fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, ``` -------------------------------- ### Query Execution Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Methods for executing Cypher queries. ```APIDOC ## Database::execute ### Description Executes a Cypher query. If no transaction is active, the call is implicitly wrapped in a transaction. ## Database::execute_with_params ### Description Executes a Cypher query with optional parameter substitution. ``` -------------------------------- ### And Then Chaining Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Calls a function if the result is Ok, otherwise returns the Err. ```rust fn sq_then_to_string(x: u32) -> Result<String, &'static str> { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### HashMap Iterator Conversion Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Demonstrates converting a HashMap into a vector of key-value pairs using into_iter(). ```rust let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); // Not possible with .iter() let vec: Vec<(&str, i32)> = map.into_iter().collect(); ``` -------------------------------- ### Retrieve Key-Value Pair with get_key_value Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Demonstrates using get_key_value to retrieve a stored key and value reference, useful when the lookup key is a borrowed form of the map key. ```rust use std::collections::HashMap; use std::hash::{Hash, Hasher}; #[derive(Clone, Copy, Debug)] struct S { id: u32, name: &'static str, // ignored by equality and hashing operations } impl PartialEq for S { fn eq(&self, other: &S) -> bool { self.id == other.id } } impl Eq for S {} impl Hash for S { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state); } } let j_a = S { id: 1, name: "Jessica" }; let j_b = S { id: 1, name: "Jess" }; let p = S { id: 2, name: "Paul" }; assert_eq!(j_a, j_b); let mut map = HashMap::new(); map.insert(j_a, "Paris"); assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris"))); assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case assert_eq!(map.get_key_value(&p), None); ``` -------------------------------- ### create_fulltext_index Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Creates a fulltext index on a specific label and property using SQLite FTS5 trigram tokenizer to accelerate string predicates. ```APIDOC ## pub fn create_fulltext_index(&mut self, label: &str, property: &str) -> Result<()> ### Description Creates a fulltext index on `(label, property)` inside the active write transaction. This accelerates `CONTAINS`, `STARTS WITH`, and `ENDS WITH` predicates using SQLite FTS5's trigram tokenizer. ### Parameters - **label** (&str) - Required - The node label to index. - **property** (&str) - Required - The property name to index. ### Errors - `GraphError::Transaction`: Returned when no write transaction is active. - `GraphError::IndexAlreadyExists`: Returned when a fulltext index on this pair already exists. ``` -------------------------------- ### create_fulltext_index_ci Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Creates a case-insensitive fulltext index on a specific label and property. ```APIDOC ## pub fn create_fulltext_index_ci(&mut self, label: &str, property: &str) -> Result<()> ### Description Creates a case-insensitive fulltext index on `(label, property)` using FTS5's `trigram case_sensitive 0` tokenizer. This makes `CONTAINS`, `STARTS WITH`, and `ENDS WITH` queries case-insensitive. ``` -------------------------------- ### pub fn values(&self) -> Values<'_, K, V> Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Returns an iterator visiting all values in arbitrary order. ```APIDOC ## pub fn values(&self) -> Values<'_, K, V> ### Description An iterator visiting all values in arbitrary order. The iterator element type is `&'a V`. ``` -------------------------------- ### HashMap Inequality Implementation Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Defines the inequality check for HashMap instances using the ne method. ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Into Ok Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the contained Ok value without panicking, requiring the error type to be Infallible. ```rust fn only_good_news() -> Result<String, !> { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Expect Error Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the Err value or panics if the result is Ok. ```rust let x: Result<u32, &str> = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### pub fn capacity(&self) -> usize Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Returns the number of elements the map can hold without reallocating. ```APIDOC ## pub fn capacity(&self) -> usize ### Description Returns the number of elements the map can hold without reallocating. This number is a lower bound. ``` -------------------------------- ### Iterate over HashMap values Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Provides an iterator over values in arbitrary order. Iteration performance is O(capacity). ```rust use std::collections::HashMap; let map: HashMap<&str, i32> = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut values: Vec<_> = map.values().copied().collect(); values.sort(); assert_eq!(values, vec![1, 2, 3]); ``` -------------------------------- ### Inspect Ok Value Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Executes a closure with a reference to the Ok value without modifying the result. ```rust let x: u8 = "4" .parse::<u8>() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Expect Result Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the Ok value or panics with a provided message if the result is Err. ```rust let x: Result<u32, &str> = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Unwrap Error Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the Err value or panics if the result is Ok. ```rust let x: Result<u32, &str> = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result<u32, &str> = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Transaction Management Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Methods for managing read and write transactions. ```APIDOC ## Database::read_tx ### Description Begins a read-only transaction using snapshot isolation via WAL. ## Database::write_tx ### Description Begins a read-write transaction using BEGIN IMMEDIATE. ## Database::begin_write ### Description Begins a read-write transaction on the handle. Subsequent execute calls run inside it until commit or rollback. ## Database::begin_read ### Description Begins a read-only transaction using BEGIN DEFERRED. ## Database::commit ### Description Commits the currently-active transaction. ## Database::rollback ### Description Rolls back the currently-active transaction. ``` -------------------------------- ### Fallback to alternative Result with or Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the provided Result if the current one is an Err, otherwise returns the Ok value. Note that arguments are eagerly evaluated. ```rust let x: Result<u32, &str> = Ok(2); let y: Result<u32, &str> = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result<u32, &str> = Err("early error"); let y: Result<u32, &str> = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result<u32, &str> = Err("not a 2"); let y: Result<u32, &str> = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result<u32, &str> = Ok(2); let y: Result<u32, &str> = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Insert key-value pair Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Add a key-value pair to the map, returning the previous value if the key existed. ```rust use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.insert(37, "a"), None); assert_eq!(map.is_empty(), false); map.insert(37, "b"); assert_eq!(map.insert(37, "c"), Some("b")); assert_eq!(map[&37], "c"); ``` -------------------------------- ### Check HashMap size Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Methods to determine the number of elements or if the map is empty. ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); ``` ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty()); ``` -------------------------------- ### HashMap Equality Implementation Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Defines the equality check for HashMap instances using the PartialEq trait. ```rust fn eq(&self, other: &HashMap<K, V, S, A>) -> bool ``` -------------------------------- ### Into Error Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the contained Err value without panicking, requiring the ok type to be Infallible. ```rust fn only_bad_news() -> Result<!, String> { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Map Result to default or fallback Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Provides default values or fallback functions when the result is an Err. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` ```rust let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### Unwrap Result Values Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Extracts the Ok value or panics if the result is Err. ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result<u32, &str> = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Record struct definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Record.html The internal structure of the Record type. ```rust pub struct Record { /* private fields */ } ``` -------------------------------- ### Database Struct Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html The internal structure of the Database type, including configuration fields for limits on properties, names, and traversal operations. ```rust pub struct Database { pub max_property_value_bytes: usize, pub max_name_bytes: usize, pub max_result_rows: usize, pub max_traversal_depth: u32, pub max_traversal_work: u64, /* private fields */ } ``` -------------------------------- ### Check Result with is_err_and Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Checks if the result is an Err and matches a specific predicate. ```rust use std::io::{Error, ErrorKind}; let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result<u32, Error> = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result<u32, String> = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Define SyncMode Enum Source: https://docs.rs/graphdblite/0.1.2/graphdblite/enum.SyncMode.html Represents the available SQLite synchronous PRAGMA modes. ```rust pub enum SyncMode { Off, Normal, Full, Extra, } ``` -------------------------------- ### Reference Result with as_ref and as_mut Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Converts a Result of values into a Result of references or mutable references. ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result<u32, &str> = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ```rust fn mutate(r: &mut Result<i32, i32>) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result<i32, i32> = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result<i32, i32> = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Consume HashMap into keys Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Creates a consuming iterator over keys. The map is moved and cannot be used afterwards. ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut vec: Vec<&str> = map.into_keys().collect(); // The `IntoKeys` iterator produces keys in arbitrary order, so the // keys must be sorted to test them against a sorted array. vec.sort_unstable(); assert_eq!(vec, ["a", "b", "c"]); ``` -------------------------------- ### Transposing Result and Option Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Converting a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result<Option<i32>, SomeErr> = Ok(Some(5)); let y: Option<Result<i32, SomeErr>> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Check for key existence Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Verify if a key exists in the map using contains_key. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.contains_key(&1), true); assert_eq!(map.contains_key(&2), false); ``` -------------------------------- ### ReadTxGuard Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.ReadTxGuard.html The structure definition for the read transaction guard. ```rust pub struct ReadTxGuard<'a> { /* private fields */ } ``` -------------------------------- ### Reserve HashMap Capacity Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Ensures the map has enough capacity for additional elements, potentially triggering reallocation. ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::new(); map.reserve(10); ``` -------------------------------- ### QueryPhase Enum Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/enum.QueryPhase.html Defines the phases of query processing: Parse, SemanticAnalysis, and Runtime. ```rust pub enum QueryPhase { Parse, SemanticAnalysis, Runtime, } ``` -------------------------------- ### PathValue::is_empty Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.PathValue.html Checks if the path is a zero-length path. ```APIDOC ## pub fn is_empty(&self) -> bool ### Description Returns true if the path is a zero-length path, meaning it contains only a single node. ``` -------------------------------- ### Check HashMap capacity Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Returns the number of elements the map can hold without reallocating. ```rust use std::collections::HashMap; let map: HashMap<i32, i32> = HashMap::with_capacity(100); assert!(map.capacity() >= 100); ``` -------------------------------- ### Map Result values Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Applies a function to the contained Ok value while leaving Err untouched. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::<i32>().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### Consume HashMap into values Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Creates a consuming iterator that visits all values in arbitrary order. The map is unusable after this operation. ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut vec: Vec<i32> = map.into_values().collect(); // The `IntoValues` iterator produces values in arbitrary order, so // the values must be sorted to test them against a sorted array. vec.sort_unstable(); assert_eq!(vec, [1, 2, 3]); ``` -------------------------------- ### Compute default value with unwrap_or_else Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the contained Ok value or computes it from a closure if the result is an Err. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### Checking Result Status Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Methods to verify if a result is Ok or Err, including predicate checks. ```rust let x: Result<i32, &str> = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result<i32, &str> = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result<u32, &str> = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result<u32, &str> = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result<String, &str> = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` ```rust let x: Result<i32, &str> = Ok(-3); assert_eq!(x.is_err(), false); let x: Result<i32, &str> = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### Convert Result to Option Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Converts a Result into an Option, discarding the error or success value respectively. ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result<u32, &str> = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.err(), None); let x: Result<u32, &str> = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### WriteTxGuard Struct Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.WriteTxGuard.html The definition of the WriteTxGuard struct. ```rust pub struct WriteTxGuard<'a> { /* private fields */ } ``` -------------------------------- ### Iterate over HashMap key-value pairs Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Provides an iterator over immutable references to key-value pairs. ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut count = 0; for (_key, _val) in map.iter() { count += 1; } assert_eq!(count, 3); ``` -------------------------------- ### Retrieve Multiple Mutable References with get_disjoint_mut Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Retrieves mutable references to multiple values in a map. Panics if duplicate keys are provided. ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); // Get Athenæum and Bodleian Library let [Some(a), Some(b)] = libraries.get_disjoint_mut([ "Athenæum", "Bodleian Library", ]) else { panic!() }; // Assert values of Athenæum and Library of Congress let got = libraries.get_disjoint_mut([ "Athenæum", "Library of Congress", ]); assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); // Missing keys result in None let got = libraries.get_disjoint_mut([ "Athenæum", "New York Public Library", ]); assert_eq!( got, [ Some(&mut 1807), None ] ); ``` ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Athenæum".to_string(), 1807); // Duplicate keys panic! let got = libraries.get_disjoint_mut([ "Athenæum", "Athenæum", ]); ``` -------------------------------- ### commit() Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.ReadTxGuard.html Releases the snapshot held by the wrapped read transaction. ```APIDOC ### pub fn commit(self) -> Result<()> Releases the snapshot held by the wrapped read transaction. ``` -------------------------------- ### get_key_value Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Retrieves the key-value pair corresponding to the supplied key, allowing for borrowed key lookups. ```APIDOC ## pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)> ### Description Returns the key-value pair corresponding to the supplied key. This is useful for key types where non-identical keys are considered equal or for retrieving the stored key reference. ### Parameters - **k** (&Q) - Required - The key to search for, which must be a borrowed form of the map's key type. ``` -------------------------------- ### Node Struct Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Node.html The primary structure definition for a node within the graph. ```rust pub struct Node { pub id: NodeId, pub labels: Vec<String>, pub properties: Properties, } ``` -------------------------------- ### Manipulate HashMap Entry Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Accesses a key's entry for in-place modification or insertion. ```rust use std::collections::HashMap; let mut letters = HashMap::new(); for ch in "a short treatise on fungi".chars() { letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1); } assert_eq!(letters[&'s'], 2); assert_eq!(letters[&'t'], 3); assert_eq!(letters[&'u'], 1); assert_eq!(letters.get(&'y'), None); ``` -------------------------------- ### rollback() Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.ReadTxGuard.html Explicitly ends the wrapped read transaction. ```APIDOC ### pub fn rollback(self) -> Result<()> Explicitly end the wrapped read transaction. Read-only txns have no writes to revert, so this is equivalent to dropping the guard. ``` -------------------------------- ### pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Returns an iterator visiting all values mutably in arbitrary order. ```APIDOC ## pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> ### Description An iterator visiting all values mutably in arbitrary order. The iterator element type is `&'a mut V`. ``` -------------------------------- ### PathValue::single Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.PathValue.html Constructs a new zero-length path containing a single node and no edges. ```APIDOC ## pub fn single(node: Node) -> Self ### Description Constructs a zero-length path consisting of a single node and zero edges. ### Parameters - **node** (Node) - Required - The starting node for the path. ``` -------------------------------- ### Retrieve disjoint mutable references Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Access multiple mutable references simultaneously when keys are guaranteed not to overlap. ```rust // SAFETY: The keys do not overlap. let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "New York Public Library", ]) }; // Missing keys result in None assert_eq!(got, [Some(&mut 1807), None]); ``` -------------------------------- ### Result Type Alias Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html The primary type alias definition for the library. ```rust pub type Result<T> = Result<T, GraphError>; ``` -------------------------------- ### Flattening Nested Results Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Reducing nesting levels in Result types. ```rust let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result<Result<&'static str, u32>, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` ```rust let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### commit Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.WriteTxGuard.html Commits the wrapped write transaction and disarms the automatic drop-rollback mechanism. ```APIDOC ### pub fn commit(self) -> Result<()> Commits the wrapped write transaction. Disarms the drop-rollback. ``` -------------------------------- ### Result Enum Structure Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html The underlying enum structure for the Result type. ```rust pub enum Result<T> { Ok(T), Err(GraphError), } ``` -------------------------------- ### rollback Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.WriteTxGuard.html Explicitly rolls back the wrapped write transaction and disarms the automatic drop-rollback mechanism. ```APIDOC ### pub fn rollback(self) -> Result<()> Roll back the wrapped write transaction explicitly. Disarms the drop-rollback (which would otherwise have rolled back anyway). ``` -------------------------------- ### pub unsafe fn unwrap_unchecked(self) -> T Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Result.html Returns the contained Ok value, consuming the self value, without checking that the value is not an Err. Calling this method on an Err is undefined behavior. ```APIDOC ## pub unsafe fn unwrap_unchecked(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value, without checking that the value is not an `Err`. ### Safety Calling this method on an `Err` is _undefined behavior_. ``` -------------------------------- ### Value Enum Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/enum.Value.html The complete definition of the Value enum, listing all 16 variants including scalar, collection, and temporal types. ```rust pub enum Value { Show 16 variants Null, Bool(bool), I64(i64), F64(f64), String(String), List(Vec<Value>), Node(Node), Edge(Edge), Path(PathValue), Map(BTreeMap<String, Value>), Date(CypherDate), LocalTime(CypherLocalTime), Time(CypherTime), LocalDateTime(CypherLocalDateTime), DateTime(CypherDateTime), Duration(CypherDuration), } ``` -------------------------------- ### Remove key from map Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Remove a key and return its associated value. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None); ``` -------------------------------- ### Edge Struct Definition Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Edge.html The definition of the Edge struct, which includes fields for source node, destination node, label, and properties. ```rust pub struct Edge { pub src: NodeId, pub dst: NodeId, pub label: String, pub properties: Properties, } ``` -------------------------------- ### drop_fulltext_index Source: https://docs.rs/graphdblite/0.1.2/graphdblite/struct.Database.html Drops an existing fulltext index. ```APIDOC ## pub fn drop_fulltext_index(&mut self, label: &str, property: &str) -> Result<()> ### Description Drops a fulltext index on `(label, property)` inside the active write transaction. ### Errors - `GraphError::IndexNotFound`: Returned when no fulltext index exists on the specified pair. ``` -------------------------------- ### Retain elements by predicate Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Removes all elements that do not satisfy the provided predicate. ```rust use std::collections::HashMap; let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect(); map.retain(|&k, _| k % 2 == 0); assert_eq!(map.len(), 4); ``` -------------------------------- ### Iterate over HashMap with mutable values Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Provides an iterator over key-value pairs allowing mutable access to the values. ```rust use std::collections::HashMap; let mut map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); // Update all values for (_, val) in map.iter_mut() { *val *= 2; } assert_eq!(map.get("a"), Some(&2)); assert_eq!(map.get("b"), Some(&4)); assert_eq!(map.get("c"), Some(&6)); ``` -------------------------------- ### get_disjoint_unchecked_mut Source: https://docs.rs/graphdblite/0.1.2/graphdblite/type.Properties.html Unsafe version of batch mutable retrieval that skips uniqueness validation. ```APIDOC ## pub unsafe fn get_disjoint_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N] ### Description Attempts to get mutable references to N values in the map at once, without validating that the values are unique. ### Safety Calling this method with overlapping keys is undefined behavior even if the resulting references are not used. ```