### Run QA Tests with Just Source: https://github.com/plabayo/venndb/blob/main/CONTRIBUTING.md This command utilizes the `just` build tool to execute the 'qa' task, which typically encompasses a suite of quality assurance tests. Ensure `just`, `Rust`, and `cargo-hack` are installed prior to running. ```bash just qa ``` -------------------------------- ### Rust Example: Defining and Querying Employee Data with venndb Source: https://github.com/plabayo/venndb/blob/main/www/index.html This Rust code snippet demonstrates how to define a data structure 'Employee' with venndb derive macros for key, filter, and skip attributes. It then shows how to initialize a database from an iterator and perform a query to find specific employees based on multiple criteria. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] pub struct Employee { #[venndb(key)] id: u32, name: String, is_manager: Option, is_admin: bool, #[venndb(skip)] foo: bool, #[venndb(filter, any)] department: Department, #[venndb(filter)] country: Option, } fn main() { let db = EmployeeDB::from_iter(/* .. */); let mut query = db.query(); let employee = query .is_admin(true) .is_manager(false) .department(Department::Engineering) .execute() .expect("to have found at least one") .any(); println!("non-manager admin engineer: {:?}", employee); } ``` -------------------------------- ### Query Multiple Filter Map Variants in Rust with Venndb Source: https://github.com/plabayo/venndb/blob/main/README.md This Rust code snippet demonstrates how to query for multiple variants of a filter map property using the Venndb library. It initializes a database with `Value` structs, then constructs a query that matches rows where the `foo` field is either 'a' or 'c'. The example shows the setup, query execution, and assertion of the results. ```rust use venndb::{Any, VennDB}; #[derive(Debug, VennDB)] pub struct Value { #[venndb(filter)] pub foo: String, pub bar: u32, } let db = ValueDB::from_iter([ Value { foo: "a".to_owned(), bar: 8, }, Value { foo: "b".to_owned(), bar: 12, }, Value { foo: "c".to_owned(), bar: 16, }, ].into_Iter()).unwrap(); let mut query = db.query(); query.foo(MyString("a".to_owned())); query.foo(MyString("c".to_owned())); let values: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(values.len(), 2); assert_eq!(values[0].bar, 8); assert_eq!(values[0].bar, 16); ``` -------------------------------- ### EmployeeInMemDB Data Retrieval (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Provides methods to retrieve specific rows from the EmployeeInMemDB based on key properties. The `get_by_id` method is shown as an example for retrieving by the 'id' key, and similar methods are generated for other properties marked with `#[venndb(key)]`. ```Rust impl EmployeeInMemDB { // look up a row by the `id` key property. pub fn get_by_id(&self, data: impl ::std::convert::Into) -> Option<&Employee> where Employee ::std::borrow::Borrow, Q: ::std::hash::Hash + ::std::cmp::Eq + ?::std::marker::Sized; // Example for another key property 'foo' // pub fn get_by_foo(&self, data: impl ::std::convert::Into) -> Option<&Employee> where Employee ::std::borrow::Borrow, Q: ::std::hash::Hash + ::std::cmp::Eq + ?::std::marker::Sized; } ``` -------------------------------- ### Get First Employee from In-Memory DB Query Result (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Retrieves a reference to the first employee found in the in-memory database query results. While it often returns the first inserted row, relying on this specific order is discouraged for compatibility reasons. ```rust impl EmployeeInMemDBQueryResult { /// return a reference to the first matched employee found. /// An implementation detail is that this will be the matched row that was first inserted, /// but for compatibility reasons you best not rely on this if you do not have to. pub fn first(&self) -> &Employee; } ``` -------------------------------- ### Add venndb Dependency with Cargo Source: https://github.com/plabayo/venndb/blob/main/www/index.html This command adds the venndb crate as a dependency to your Rust project using Cargo, the Rust package manager. Ensure you have Cargo installed and configured. ```bash cargo add venndb ``` -------------------------------- ### VennDB Database Creation Methods Source: https://context7.com/plabayo/venndb/llms.txt Illustrates various methods for creating and populating a VennDB database, including `new()` for an empty database, `with_capacity()` for pre-allocation, `from_rows()` from a `Vec`, and `from_iter()` from any iterator. Error handling for duplicate keys is mentioned. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] struct Product { #[venndb(key)] sku: String, in_stock: bool, is_featured: bool, } fn main() { // Empty database let mut db = ProductDB::new(); assert_eq!(db.len(), 0); // With pre-allocated capacity let mut db = ProductDB::with_capacity(100); assert_eq!(db.capacity(), 100); // From Vec of rows let products = vec![ Product { sku: "ABC-001".to_string(), in_stock: true, is_featured: false }, Product { sku: "ABC-002".to_string(), in_stock: false, is_featured: true }, ]; let db = ProductDB::from_rows(products).unwrap(); assert_eq!(db.len(), 2); // From iterator with type conversion let db = ProductDB::from_iter([ Product { sku: "XYZ-001".to_string(), in_stock: true, is_featured: true }, ]).unwrap(); // Iterate over all rows for product in db.iter() { println!("SKU: {}, In Stock: {}", product.sku, product.in_stock); } // Convert back to Vec let rows = db.into_rows(); assert_eq!(rows.len(), 1); } ``` -------------------------------- ### Get Random Employee from In-Memory DB Query Result (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Returns a reference to a randomly selected employee from the in-memory database query results. The selection is guaranteed to be fair. ```rust impl EmployeeInMemDBQueryResult { /// return a reference to a randomly selected matched employee. /// The randomness can be relied upon to be fair. pub fn any(&self) -> &Employee; } ``` -------------------------------- ### EmployeeInMemDB Constructors (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Provides methods to create new EmployeeInMemDB instances. Supports creation with zero capacity, a specified capacity, or directly from a vector or iterator of Employee data. Error handling is included for methods that might fail due to key constraints or invalid data. ```Rust impl EmployeeInMemDB { // create a new database with zero capacity pub fn new() -> Self; // same as EmployeeInMemDB::new() -> EmployeeInMemDB pub fn default() -> Self; // create a new database with the given capacity, but no rows already inserted pub fn capacity(capacity: usize) -> Self; // constructor to create the database directly from a heap-allocated list of data instances. pub fn from_rows(rows: ::std::vec::Vec) -> Self; // constructor to create the database directly from a heap-allocated list of data instances with error handling. pub fn from_rows(rows: ::std::vec::Vec) -> Result>>; // Same as from_rows but using an iterator instead. pub fn from_iter(iter: impl ::std::iter::IntoIterator>) -> Self; // Same as from_rows but using an iterator instead with error handling. pub fn from_iter(iter: impl ::std::iter::IntoIterator>) -> Result>>; } ``` -------------------------------- ### Recreate DB from Rows Source: https://github.com/plabayo/venndb/blob/main/README.md Demonstrates recreating the EmployeeInMemDB from a Vec of Employee rows. It asserts that the database is created without errors and that the correct number of rows are present. ```rust let mut db = EmployeeInMemDB::from_rows(employees).expect("DB created without errors"); assert_eq!(db.iter().count(), 8); ``` -------------------------------- ### Run All Tests with Features Source: https://github.com/plabayo/venndb/blob/main/CONTRIBUTING.md This command executes all tests for the venndb workspace, including those enabled by all features. It's a standard way to ensure comprehensive test coverage locally. ```bash cargo test --all-features --workspace ``` -------------------------------- ### Integrating VennDB with Rust's From Trait (Rust) Source: https://context7.com/plabayo/venndb/llms.txt Shows how VennDB integrates with Rust's `From` trait, enabling data insertion from types that can be converted into the database row type. This facilitates cleaner data handling by separating input formats from the database model. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] struct Employee { #[venndb(key)] id: u32, name: String, is_manager: bool, is_admin: bool, } // Input format from external source struct CsvRow { id: u32, name: String, role: String, } impl From for Employee { fn from(row: CsvRow) -> Self { Employee { id: row.id, name: row.name, is_manager: row.role == "manager" || row.role == "admin", is_admin: row.role == "admin", } } } fn main() { // Create DB directly from CSV rows let db = EmployeeDB::from_iter([ CsvRow { id: 1, name: "Alice".to_string(), role: "admin".to_string() }, CsvRow { id: 2, name: "Bob".to_string(), role: "manager".to_string() }, CsvRow { id: 3, name: "Carol".to_string(), role: "engineer".to_string() }, ]).unwrap(); // Append individual converted rows let mut db = EmployeeDB::new(); db.append(CsvRow { id: 1, name: "Alice".to_string(), role: "admin".to_string() }).unwrap(); let alice = db.get_by_id(&1).unwrap(); assert!(alice.is_admin); assert!(alice.is_manager); } ``` -------------------------------- ### Create and Query VennDB In-Memory Database (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Demonstrates creating an in-memory VennDB from CSV data, retrieving records by ID, and performing filtered queries based on struct fields. It uses `expect` for error handling and `assert_eq` for verification. ```rust fn main() { let db = EmployeeInMemDB::from_iter([ RawCsvRow("1,John Doe,true,false,true,false,Engineering,USA"), RawCsvRow("2,Jane Doe,false,true,true,true,Sales,"), RawCsvRow("3,John Smith,false,false,,false,Marketing,"), RawCsvRow("4,Jane Smith,true,true,false,true,HR,"), RawCsvRow("5,John Johnson,true,true,true,true,Engineering,"), RawCsvRow("6,Jane Johnson,false,false,,false,Sales,BE"), RawCsvRow("7,John Brown,true,false,true,false,Marketing,BE"), RawCsvRow("8,Jane Brown,false,true,true,true,HR,BR"), ]) .expect("MemDB created without errors (e.g. no duplicate keys)"); println!(">>> Printing all employees..."); let all_employees: Vec<_> = db.iter().collect(); assert_eq!(all_employees.len(), 8); println!("All employees: {:#?}", all_employees); println!(">>> You can lookup an employee by any registered key..."); let employee = db .get_by_id(&2) .expect("to have found an employee with ID 2"); assert_eq!(employee.name, "Jane Doe"); println!(">>> Querying for all managers..."); let mut query = db.query(); query.is_manager(true); let managers: Vec<_> = query .execute() .expect("to have found at least one") .iter() .collect(); assert_eq!(managers.len(), 4); assert_eq!( managers.iter().map(|e| e.id).sorted().collect::>(), [1, 4, 5, 7] ); println!(">>> Querying for all managers with a last name of 'Johnson'..."); let managers_result = query .execute() .expect("to have found at least one") .filter(|e| e.name.ends_with("Johnson")) .expect("to have found a manager with a last name of Johnson"); let managers = managers_result.iter().collect::>(); assert_eq!(managers.len(), 1); assert_eq!(managers.iter().map(|e| e.id).collect::>(), [5]); println!(">>> You can also just get the first result if that is all you care about..."); let manager = managers_result.first(); assert_eq!(manager.id, 5); println!(">>> Querying for a random active manager in the Engineering department..."); let manager = query .reset() .is_active(true) .is_manager(true) .department(Department::Engineering) .execute() .expect("to have found at least one") .any(); } ``` -------------------------------- ### Append and Extend Data in VennDB (Rust) Source: https://context7.com/plabayo/venndb/llms.txt Demonstrates appending a single row using `append()` and multiple rows using `extend()` to a VennDB database. It also shows how to handle `DuplicateKey` errors and recover the rejected input. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] struct User { #[venndb(key)] email: String, is_active: bool, is_verified: bool, } fn main() { let mut db = UserDB::new(); // Append single row db.append(User { email: "alice@example.com".to_string(), is_active: true, is_verified: true, }).unwrap(); // Append returns error on duplicate key let result = db.append(User { email: "alice@example.com".to_string(), // Duplicate! is_active: false, is_verified: false, }); assert!(result.is_err()); let err = result.unwrap_err(); assert_eq!(err.kind(), UserDBErrorKind::DuplicateKey); // Recover the rejected row let rejected_user = err.into_input(); assert_eq!(rejected_user.email, "alice@example.com"); // Extend with multiple rows db.extend([ User { email: "bob@example.com".to_string(), is_active: true, is_verified: false }, User { email: "carol@example.com".to_string(), is_active: false, is_verified: true }, ]).unwrap(); assert_eq!(db.len(), 3); } ``` -------------------------------- ### Structs with Multiple Keys in VennDB (Rust) Source: https://context7.com/plabayo/venndb/llms.txt Demonstrates how to define a struct with multiple fields marked as keys using `#[venndb(key)]`. This allows VennDB to generate separate lookup methods for each key, enforcing unique values across all rows for each key. Duplicate detection is handled automatically. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] struct User { #[venndb(key)] id: u32, #[venndb(key)] email: String, #[venndb(key)] username: String, is_admin: bool, } fn main() { let db = UserDB::from_iter([ User { id: 1, email: "alice@example.com".to_string(), username: "alice".to_string(), is_admin: true }, User { id: 2, email: "bob@example.com".to_string(), username: "bob".to_string(), is_admin: false }, ]).unwrap(); // Look up by any key let by_id = db.get_by_id(&1).unwrap(); let by_email = db.get_by_email("alice@example.com").unwrap(); let by_username = db.get_by_username("alice").unwrap(); // All return the same user assert_eq!(by_id.id, by_email.id); assert_eq!(by_email.id, by_username.id); // Duplicate on any key causes error let mut db2 = UserDB::new(); db2.append(User { id: 1, email: "test@example.com".to_string(), username: "test".to_string(), is_admin: false }).unwrap(); // Fails: duplicate id let err = db2.append(User { id: 1, email: "other@example.com".to_string(), username: "other".to_string(), is_admin: false }).unwrap_err(); assert_eq!(err.kind(), UserDBErrorKind::DuplicateKey); } ``` -------------------------------- ### Implementing 'Any' for Filter Values in VennDB (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Demonstrates how to implement the `Any` trait for an enum to allow filter values to match all other values in a VennDB. This is useful for creating a wildcard or 'any' option in your filterable properties. It shows how to define the enum, implement `Any`, and use it within a `VennDB` struct. ```rust use venndb::{Any, VennDB}; #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub enum Department { Any, Hr, Engineering, } impl Any for Department { fn is_any(&self) -> bool { self == Department::Any } } #[derive(Debug, VennDB)] pub struct Employee { name: String, #[venndb(filter, any)] department: Department, } // Example Usage: // let db = EmployeeDB::from_iter([ // Employee { name: "Jack".to_owned(), department: Department::Any }, // Employee { name: "Derby".to_owned(), department: Department::Hr }, // ]); // let mut query = db.query(); // let hr_employees: Vec<_> = query.department(Department::Hr).execute().unwrap().iter().collect(); // assert_eq!(hr_employees.len(), 2); ``` -------------------------------- ### Accessing VennDB Query Results: first(), any(), iter(), filter() in Rust Source: https://context7.com/plabayo/venndb/llms.txt Demonstrates how to access query results from VennDB using `first()` for the first match, `any()` for a random match, `iter()` to iterate all matches, and `filter()` to apply additional predicates. Useful for various data retrieval scenarios, including load balancing. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] struct Proxy { #[venndb(key)] id: u32, is_available: bool, supports_https: bool, #[venndb(filter)] country: String, } fn main() { let db = ProxyDB::from_iter([ Proxy { id: 1, is_available: true, supports_https: true, country: "US".to_string() }, Proxy { id: 2, is_available: true, supports_https: false, country: "US".to_string() }, Proxy { id: 3, is_available: true, supports_https: true, country: "DE".to_string() }, Proxy { id: 4, is_available: false, supports_https: true, country: "US".to_string() }, ]).unwrap(); let mut query = db.query(); query.is_available(true).country("US".to_string()); let result = query.execute().unwrap(); // Get first match (deterministic) let first = result.first(); assert_eq!(first.id, 1); // Get random match (fair distribution for load balancing) let random = result.any(); assert!(random.id == 1 || random.id == 2); // Iterate all matches let all: Vec<_> = result.iter().collect(); assert_eq!(all.len(), 2); // Apply additional filter predicate let https_only = result.filter(|p| p.supports_https).unwrap(); let filtered: Vec<_> = https_only.iter().collect(); assert_eq!(filtered.len(), 1); assert_eq!(filtered[0].id, 1); // Filter can return None if no matches let impossible = result.filter(|p| p.id > 100); assert!(impossible.is_none()); } ``` -------------------------------- ### VennDB Derive Macro for Structs Source: https://context7.com/plabayo/venndb/llms.txt Demonstrates how to use the `#[derive(VennDB)]` macro to automatically generate a database implementation for a Rust struct. This includes defining key fields, boolean filters, custom filters, and skipping fields. The generated database is named `{StructName}DB`. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] pub struct Employee { #[venndb(key)] // Creates get_by_id() lookup method id: u32, name: String, is_manager: bool, // Auto-generates is_manager() filter is_admin: bool, // Auto-generates is_admin() filter #[venndb(skip)] // Excluded from filtering internal_flag: bool, #[venndb(filter)] // Non-bool filter (requires PartialEq + Eq + Hash + Clone) department: Department, } #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum Department { Engineering, Sales, Marketing, HR, } fn main() { // Create database from iterator let db = EmployeeDB::from_iter([ Employee { id: 1, name: "Alice".to_string(), is_manager: true, is_admin: false, internal_flag: false, department: Department::Engineering, }, Employee { id: 2, name: "Bob".to_string(), is_manager: false, is_admin: true, internal_flag: true, department: Department::Sales, }, ]).unwrap(); // Key lookup - O(1) let alice = db.get_by_id(&1).unwrap(); assert_eq!(alice.name, "Alice"); // Query with filters let mut query = db.query(); query.is_manager(true).department(Department::Engineering); let managers: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(managers.len(), 1); assert_eq!(managers[0].id, 1); } ``` -------------------------------- ### VennDB Query Builder and Filters (Rust) Source: https://context7.com/plabayo/venndb/llms.txt Illustrates using the VennDB query builder to filter data. It shows how to chain filters for AND logic, use multiple values for OR logic on the same filter, and reset filters. Boolean fields and fields marked with `#[venndb(filter)]` can be used for filtering. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] struct Server { #[venndb(key)] hostname: String, is_healthy: bool, is_primary: bool, has_ssl: bool, #[venndb(filter)] region: String, #[venndb(filter)] tier: Tier, } #[derive(Debug, PartialEq, Eq, Hash, Clone)] enum Tier { Free, Pro, Enterprise } fn main() { let db = ServerDB::from_iter([ Server { hostname: "us-east-1".to_string(), is_healthy: true, is_primary: true, has_ssl: true, region: "US".to_string(), tier: Tier::Enterprise }, Server { hostname: "us-east-2".to_string(), is_healthy: true, is_primary: false, has_ssl: true, region: "US".to_string(), tier: Tier::Pro }, Server { hostname: "eu-west-1".to_string(), is_healthy: false, is_primary: true, has_ssl: true, region: "EU".to_string(), tier: Tier::Enterprise }, Server { hostname: "ap-south-1".to_string(), is_healthy: true, is_primary: false, has_ssl: false, region: "APAC".to_string(), tier: Tier::Free }, ]).unwrap(); // Chain multiple filters (AND logic) let mut query = db.query(); query.is_healthy(true).has_ssl(true).tier(Tier::Enterprise); let results: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(results.len(), 1); assert_eq!(results[0].hostname, "us-east-1"); // Multiple values for same filter (OR logic) query.reset(); query.region("US".to_string()).region("EU".to_string()); let results: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(results.len(), 3); // All US and EU servers // Reset and reuse query query.reset(); query.is_healthy(true); let healthy_count = query.execute().unwrap().iter().count(); assert_eq!(healthy_count, 3); } ``` -------------------------------- ### Rust Benchmark Test Function Source: https://github.com/plabayo/venndb/blob/main/README.md This Rust function, `test_db`, is used to benchmark different proxy database implementations. It takes a generic `ProxyDB` trait object and performs lookups for a given round, pool, and country. The `divan::black_box` function is used to prevent the compiler from optimizing away the operations being benchmarked. ```rust fn test_db(db: &impl ProxyDB) { let i = next_round(); let pool = POOLS[i % POOLS.len()]; let country = COUNTRIES[i % COUNTRIES.len()]; let result = db.get(i as u64); divan::black_box(result); let result = db.any_tcp(pool, country); divan::black_box(result); let result = db.any_socks5_isp(pool, country); divan::black_box(result); } ``` -------------------------------- ### Wildcard Matching with `Any` Trait in Rust Source: https://context7.com/plabayo/venndb/llms.txt Demonstrates how to use the `#[venndb(any)]` attribute and implement the `venndb::Any` trait to enable wildcard matching in VennDB filters. This allows specific enum variants to match any query value for that field, useful for catch-all scenarios. ```rust use venndb::{Any, VennDB}; #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum Region { Any, // Wildcard value NorthAmerica, Europe, Asia, } impl Any for Region { fn is_any(&self) -> bool { self == &Region::Any } } #[derive(Debug, VennDB)] struct Endpoint { #[venndb(key)] url: String, is_active: bool, #[venndb(filter, any)] // Enable wildcard matching region: Region, } fn main() { let db = EndpointDB::from_iter([ Endpoint { url: "https://us.api.com".to_string(), is_active: true, region: Region::NorthAmerica }, Endpoint { url: "https://eu.api.com".to_string(), is_active: true, region: Region::Europe }, Endpoint { url: "https://global.api.com".to_string(), is_active: true, region: Region::Any }, // Matches all regions ]).unwrap(); // Query for Europe - matches both EU endpoint AND global (Any) endpoint let mut query = db.query(); query.region(Region::Europe); let results: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(results.len(), 2); // eu.api.com and global.api.com // Query for Asia - only global endpoint matches (no Asia-specific endpoint) query.reset().region(Region::Asia); let results: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(results.len(), 1); assert_eq!(results[0].url, "https://global.api.com"); // Query for Any specifically - only returns rows with Any value query.reset().region(Region::Any); let results: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(results.len(), 1); assert_eq!(results[0].url, "https://global.api.com"); } ``` -------------------------------- ### From Implementation for RawCsvRow to Employee Source: https://github.com/plabayo/venndb/blob/main/README.md Implements the `From` trait for `RawCsvRow` to convert it into an `Employee` struct. This involves parsing a comma-separated string into the respective employee fields. ```rust impl From> for Employee where S: AsRef, { fn from(RawCsvRow(s): RawCsvRow) -> Employee { let mut parts = s.as_ref().split(','); let id = parts.next().unwrap().parse().unwrap(); let name = parts.next().unwrap().to_string(); ``` -------------------------------- ### EmployeeInMemDB Query Builder (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Enables the construction of complex queries against the EmployeeInMemDB. The `query` method returns an `EmployeeInMemDBQuery` builder, which allows setting various filters (e.g., `is_manager`, `department`) before executing the query. ```Rust impl EmployeeInMemDB { // create a `EmployeeInMemDBQuery` builder to compose a filter composition to query the database. pub fn query(&self) -> EmployeeInMemDBQuery; } impl EmployeeInMemDBQuery { // reset the query, bringing it back to the clean state it has on creation pub fn reset(&mut self) -> &mut Self; // a filter setter for a `bool` filter. pub fn is_manager(&mut self, value: bool) -> &mut Self; // a filter (map) setter for a non-`bool` filter. pub fn department(&mut self, value: impl ::std::convert::Into) -> &mut Self; // return the result of the query using the set filters. pub fn execute(&self) -> Option>; } ``` -------------------------------- ### Retrieve All Employees as Vec Source: https://github.com/plabayo/venndb/blob/main/README.md Retrieves all employees from the database and collects them into a Vec. It then asserts the total number of employees and a specific property of the second employee in the list. ```rust let employees = db.into_rows(); assert_eq!(employees.len(), 8); assert!(employees[1].foo); println!("All employees: {:?}", employees); ``` -------------------------------- ### Query New Employee by Department and Manager Status Source: https://github.com/plabayo/venndb/blob/main/README.md Queries for a newly added employee based on their department ('Engineering') and manager status (false). It asserts the number of results and the ID of the found employee. ```rust let mut query = db.query(); query.department(Department::Engineering).is_manager(false); let new_employee: Vec<_> = query .execute() .expect("to have found at least one") .iter() .collect(); assert_eq!(new_employee.len(), 1); assert_eq!(new_employee[0].id, 9); ``` -------------------------------- ### Using Optional Filters with Option in VennDB (Rust) Source: https://context7.com/plabayo/venndb/llms.txt Explains how to use optional filters in VennDB by wrapping filter fields with `Option`. This allows for querying data where some fields might be `None`, excluding those rows from specific filter queries while still allowing them to be accessed by other means. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] struct Contact { #[venndb(key)] id: u32, is_subscribed: Option, // Optional bool filter #[venndb(filter)] country: Option, // Optional filter map } fn main() { let db = ContactDB::from_iter([ Contact { id: 1, is_subscribed: Some(true), country: Some("US".to_string()) }, Contact { id: 2, is_subscribed: Some(false), country: Some("UK".to_string()) }, Contact { id: 3, is_subscribed: None, country: None }, // Incomplete data Contact { id: 4, is_subscribed: Some(true), country: None }, ]).unwrap(); // Query subscribed contacts - only matches rows with Some(true) let mut query = db.query(); query.is_subscribed(true); let subscribed: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(subscribed.len(), 2); // IDs 1 and 4 // Query by country - rows with None country are excluded query.reset().country("US".to_string()); let us_contacts: Vec<_> = query.execute().unwrap().iter().collect(); assert_eq!(us_contacts.len(), 1); assert_eq!(us_contacts[0].id, 1); // Default query returns all rows let all: Vec<_> = db.query().execute().unwrap().iter().collect(); assert_eq!(all.len(), 4); } ``` -------------------------------- ### Query Active Sales Employees Source: https://github.com/plabayo/venndb/blob/main/README.md Queries the database for active employees in the 'Sales' department. It sets filters for 'is_active' and 'department', executes the query, and asserts the number and name of the found employee. ```rust let mut query = db.query(); query.is_active(true); query.department(Department::Sales); let sales_employees: Vec<_> = query .execute() .expect("to have found at least one") .iter() .collect(); assert_eq!(sales_employees.len(), 1); assert_eq!(sales_employees[0].name, "Jane Doe"); ``` -------------------------------- ### Custom Database Naming with `name` Attribute in Rust Source: https://context7.com/plabayo/venndb/llms.txt Demonstrates how to specify a custom name for the generated database struct using the `#[venndb(name = "CustomName")]` attribute. This overrides the default naming convention (e.g., `StructNameDB`) and also renames associated error types. ```rust use venndb::VennDB; #[derive(Debug, VennDB)] #[venndb(name = "EmployeeSheet")] struct Employee { #[venndb(key)] id: u32, name: String, is_manager: bool, } fn main() { // Database is named EmployeeSheet instead of EmployeeDB let db = EmployeeSheet::from_iter([ Employee { id: 1, name: "Alice".to_string(), is_manager: true }, Employee { id: 2, name: "Bob".to_string(), is_manager: false }, ]).unwrap(); let alice = db.get_by_id(&1).unwrap(); assert_eq!(alice.name, "Alice"); // Error type is also renamed let mut db2 = EmployeeSheet::new(); db2.append(Employee { id: 1, name: "Test".to_string(), is_manager: false }).unwrap(); let err = db2.append(Employee { id: 1, name: "Duplicate".to_string(), is_manager: false }).unwrap_err(); assert_eq!(err.kind(), EmployeeSheetErrorKind::DuplicateKey); } ``` -------------------------------- ### Extend Database with Iterator Source: https://github.com/plabayo/venndb/blob/main/README.md Extends the database with multiple employees provided as an iterator of `RawCsvRow`. It then queries for employees matching specific criteria (HR department, manager, active) and asserts the result. ```rust db.extend([ RawCsvRow("10,Glenn Doe,false,true,true,true,Engineering,"), RawCsvRow("11,Peter Miss,true,true,true,true,HR,USA"), ]) .unwrap(); let mut query = db.query(); query .department(Department::HR) .is_manager(true) .is_active(true) .is_admin(true); let employees: Vec<_> = query .execute() .expect("to have found at least one") .iter() .collect(); assert_eq!(employees.len(), 1); assert_eq!(employees[0].id, 11); ``` -------------------------------- ### Query Employees by Country (USA) After Extension Source: https://github.com/plabayo/venndb/blob/main/README.md Queries for employees from 'USA' after extending the database. It asserts the total count of US employees and verifies their IDs. ```rust query.reset().country("USA".to_owned()); let employees: Vec<_> = query .execute() .expect("to have found at least one") .iter() .collect(); assert_eq!(employees.len(), 2); assert_eq!( employees.iter().map(|e| e.id).sorted().collect::>(), [1, 11] ); ``` -------------------------------- ### Query Active Managers in Engineering Source: https://github.com/plabayo/venndb/blob/main/README.md Queries for active managers in the 'Engineering' department. It asserts the number of results and verifies their IDs, demonstrating that previously added data remains accessible. ```rust query .reset() .is_active(true) .is_manager(true) .department(Department::Engineering); let managers: Vec<_> = query .execute() .expect("to have found at least one") .iter() .collect(); assert_eq!(managers.len(), 2); assert_eq!( managers.iter().map(|e| e.id).sorted().collect::>(), [1, 5] ); ``` -------------------------------- ### Employee Struct with VennDB Macro (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Defines the Employee struct with fields like id, name, and department. Uses the VennDB derive macro to generate database-related structures and configurations, including key and filter specifiers. ```rust #[derive(Debug, VennDB)] #[venndb(name = "EmployeeInMemDB", validator = employee_validator)] pub struct Employee { #[venndb(key)] id: u32, name: String, is_manager: bool, is_admin: bool, is_active: Option, #[venndb(skip)] foo: bool, #[venndb(filter)] department: Department, country: Option, } ``` -------------------------------- ### Query Employees by Country Source: https://github.com/plabayo/venndb/blob/main/README.md Queries the database for employees from a specific country ('USA'). It resets any previous query filters, sets the 'country' filter, executes the query, and asserts the number and ID of the found employee. ```rust query.reset().country("USA".to_owned()); let usa_employees: Vec<_> = query .execute() .expect("to have found at least one") .iter() .collect(); assert_eq!(usa_employees.len(), 1); assert_eq!(usa_employees[0].id, 1); ``` -------------------------------- ### Append Employee with Duplicate Key Source: https://github.com/plabayo/venndb/blob/main/README.md Attempts to append a new employee with an ID that already exists in the database. This is expected to fail with a 'DuplicateKey' error, which is then asserted. ```rust assert_eq!(EmployeeInMemDBErrorKind::DuplicateKey, db .append(RawCsvRow("8,John Doe,true,false,true,false,Engineering,")) .unwrap_err().kind()); ``` -------------------------------- ### Department Enum and FromStr Implementation (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Defines a Department enum with variants for Engineering, Sales, Marketing, and HR. Implements the std::str::FromStr trait to parse string slices into Department enum variants, returning an error for unrecognized strings. ```rust #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum Department { Engineering, Sales, Marketing, HR, } impl std::str::FromStr for Department { type Err = (); fn from_str(s: &str) -> Result { match s { "Engineering" => Ok(Department::Engineering), "Sales" => Ok(Department::Sales), "Marketing" => Ok(Department::Marketing), "HR" => Ok(Department::HR), _ => Err(()), } } } ``` -------------------------------- ### Iterate Over In-Memory DB Query Results (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Provides an iterator for the query results, allowing iteration over all found employees. This iterator can be used to collect results into an owned data structure. ```rust impl EmployeeInMemDBQueryResult { /// return an iterator for the query result, which will allow you to iterate over all found results, /// and as such also collect them into an owned data structure should you wish. pub fn iter(&self) -> EmployeeInMemDBQueryResultIter; } ``` -------------------------------- ### Append Valid New Employee Source: https://github.com/plabayo/venndb/blob/main/README.md Appends a new employee with a unique ID to the database. It asserts that the append operation is successful and that the database size increases. ```rust assert!(db .append(RawCsvRow("9,John Doe,false,true,true,false,Engineering,")) .is_ok()); assert_eq!(db.len(), 9); ``` -------------------------------- ### Query Inactive Employees Source: https://github.com/plabayo/venndb/blob/main/README.md Queries the database for inactive employees. It initializes a query, sets the 'is_active' filter to false, executes the query, and asserts the number and ID of the inactive employee found. ```rust let mut query = db.query(); query.is_active(false); let inactive_employees: Vec<_> = query .execute() .expect("to have found at least one") .iter() .collect(); assert_eq!(inactive_employees.len(), 1); assert_eq!(inactive_employees[0].id, 4); ``` -------------------------------- ### Parsing Employee Data from String Parts (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Parses boolean, optional boolean, string, and Department enum values from iterator parts. Handles empty strings for optional fields. Assumes correct parsing and order of parts. ```rust let is_manager = parts.next().unwrap().parse().unwrap(); let is_admin = parts.next().unwrap().parse().unwrap(); let is_active = match parts.next().unwrap() { "" => None, s => Some(s.parse().unwrap()), }; let foo = parts.next().unwrap().parse().unwrap(); let department = parts.next().unwrap().parse().unwrap(); let country = match parts.next().unwrap() { "" => None, s => Some(s.to_string()), }; Employee { id, name, is_manager, is_admin, is_active, foo, department, country, } } } ``` -------------------------------- ### VennDB 'Any' Filter Value Behavior (Rust) Source: https://github.com/plabayo/venndb/blob/main/README.md Illustrates the specific behavior of 'any' filter values in VennDB. When a filter property is marked with `any`, the corresponding 'any' value (e.g., `"*"` for a string) will only match rows that explicitly have that 'any' value set for that property. It will not match rows where the property has a different, non-any value, even if conceptually related. ```rust use venndb::{Any, VennDB}; #[derive(Debug, VennDB)] pub struct Value { #[venndb(filter, any)] pub foo: MyString, pub bar: u32, } #[derive(Debug)] pub struct MyString(String); impl Any for MyString { fn is_any(&self) -> bool { self.0 == "*" } } // Example Usage: // let db = ValueDB::from_iter([ // Value { // foo: MyString("foo".to_owned()), // bar: 8, // }, // Value { // foo: MyString("*".to_owned()), // bar: 16, // } // ].into_Iter()).unwrap(); // // let mut query = db.query(); // query.foo(MyString("*".to_owned())); // let value = query.execute().unwrap().any(); // // this will never match the row with bar == 8, // // tiven foo != an any value // assert_eq!(value.bar, 16); ```