Rust Query Builder
A powerful, type-safe query builder library for Rust that leverages key-paths for SQL-like operations on in-memory collections. This library brings the expressiveness of SQL to Rust's collections with compile-time type safety.
🎯 v0.5.0 - Extension Trait & Derive Macros! Call
.query()and.lazy_query()directly on containers - see extension guide
⚡ v0.5.0 - Build Optimized! Split into 3 crates - 65% faster builds, 6KB umbrella crate - see build guide
🎨 v0.4.0 - Helper Macros! 12 macros to reduce boilerplate - save 20-45 characters per operation - see macro guide
📦 v0.3.0 - Container Support! Query Vec, HashMap, HashSet, BTreeMap, VecDeque, and more - see container guide
⚡ v0.3.0 - Lazy Evaluation! New
LazyQuerywith deferred execution and early termination - see lazy guide
🚀 v0.2.0 - Performance Optimized! Most operations now work without
Clone- see optimization guide
🔒 Memory Safe! Using
'staticbounds causes 0 memory leaks - verified with tests ✅
💡 New! See how SQL queries map to Rust Query Builder in our SQL Comparison Example - demonstrates 15 SQL patterns side-by-side!
✅ Verified! All query results are exact SQL equivalents - see verification tests (17/17 tests passing)
Features
- 🔒 Type-safe queries: Compile-time type checking using key-paths
- 📊 SQL-like operations: WHERE, SELECT, ORDER BY, GROUP BY, JOIN
- 🧮 Rich aggregations: COUNT, SUM, AVG, MIN, MAX
- 📄 Pagination: LIMIT and SKIP operations
- 🔗 Join operations: INNER JOIN, LEFT JOIN, RIGHT JOIN, CROSS JOIN
- ⚡ Zero-cost abstractions: Leverages Rust's zero-cost abstractions
- 🎯 Fluent API: Chain operations naturally
- 🚀 Clone-free operations: Most operations work without
Clone- details - ⚡ Lazy evaluation: Deferred execution with early termination - up to 1000x faster - details
- 📦 Multiple containers: Vec, HashMap, HashSet, BTreeMap, VecDeque, arrays, and more - details
- 🎨 Helper macros: 12 macros to reduce boilerplate - 30% less code - details
- 🎯 Extension trait: Call
.query()and.lazy_query()directly on containers - details - 📝 Derive macros: Auto-generate query helpers with
#[derive(QueryBuilder)]- details
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
= "1.0.1"
= "0.5.0"
Quick Start
Extension Trait (Easiest)
use QueryExt; // Extension trait
use Keypaths;
// Note: Clone not required for most operations!
let products = vec!;
// Call .query() directly on Vec!
let query = products.query.where_;
let expensive = query.all;
// Or use lazy queries for better performance
let cheap: = products
.lazy_query
.where_
.collect;
Standard Query (Eager)
use Query;
use Keypaths;
Lazy Query (Deferred Execution - NEW in v0.3.0!)
use LazyQuery;
use Keypaths;
Core Operations
Filtering with where_
Filter collections using type-safe key-paths:
let query = new
.where_;
let electronics = query.all;
// Multiple conditions
let query2 = new
.where_
.where_
.where_;
let premium_electronics = query2.all;
Selecting Fields with select
Project specific fields from your data:
// Get all product names
let names: = new
.select;
// Get prices of electronics
let prices: = new
.where_
.select;
Ordering Results
Sort results by any field:
// Sort by price (ascending)
let by_price = new
.order_by_float;
// Sort by name (descending)
let by_name_desc = new
.order_by_desc;
// Sort with filtering
let sorted_electronics = new
.where_
.order_by_float;
Aggregations
Compute statistics over your data:
let electronics = new
.where_;
// Count
let count = electronics.count;
// Sum
let total_value: f64 = electronics.sum;
// Average
let avg_price = electronics.avg.unwrap_or;
// Min and Max
let cheapest = electronics.min_float;
let most_expensive = electronics.max_float;
Grouping with group_by
Group data by field values:
use HashMap;
// Group products by category
let by_category: = new
.group_by;
// Calculate statistics per group
for in &by_category
Pagination
Limit and skip results for pagination:
// Get first 10 products
let query = new;
let first_page = query.limit;
// Get second page (skip 10, take 10)
let query = new;
let second_page = query.skip.limit;
// Get first matching item
let query = new
.where_;
let first = query.first;
Join Operations
Combine multiple collections with type-safe joins:
use JoinQuery;
let users = vec!;
let orders = vec!;
// Inner join: users with their orders
let user_orders = new
.inner_join;
// Left join: all users, with or without orders
let all_users_orders = new
.left_join;
// Join with filter: only high-value orders
let high_value = new
.inner_join_where;
Available Join Types
- Inner Join: Returns only matching pairs
- Left Join: Returns all left items with optional right matches
- Right Join: Returns all right items with optional left matches
- Cross Join: Returns Cartesian product of both collections
- Join Where: Inner join with additional predicates
Advanced Examples
Complex Multi-Stage Query
// Find top 5 expensive electronics in stock, ordered by rating
let top_electronics = new
.where_
.where_
.where_
.order_by_float_desc;
for product in top_electronics.iter.take
Three-Way Join
// First join: Orders with Users
let orders_users = new
.inner_join;
// Second join: Add Products
let mut complete_orders = Vecnew;
for in orders_users
Category Sales Analysis
// Join orders with products, then aggregate by category
let order_products = new
.inner_join;
let mut category_sales: = new;
for in order_products
API Reference
Query Methods
new(data: &[T])- Create a new querywhere_(path, predicate)- Filter by predicateall()- Get all matching itemsfirst()- Get first matching itemcount()- Count matching itemslimit(n)- Limit resultsskip(n)- Skip results for paginationorder_by(path)- Sort ascendingorder_by_desc(path)- Sort descendingorder_by_float(path)- Sort f64 ascendingorder_by_float_desc(path)- Sort f64 descendingselect(path)- Project fieldgroup_by(path)- Group by fieldsum(path)- Sum numeric fieldavg(path)- Average of f64 fieldmin(path)/max(path)- Min/max of Ord fieldmin_float(path)/max_float(path)- Min/max of f64 fieldexists()- Check if any match
JoinQuery Methods
new(left, right)- Create a new join queryinner_join(left_key, right_key, mapper)- Inner joinleft_join(left_key, right_key, mapper)- Left joinright_join(left_key, right_key, mapper)- Right joininner_join_where(left_key, right_key, predicate, mapper)- Filtered joincross_join(mapper)- Cartesian product
Running Examples
# Advanced query builder example
# Join operations example
# SQL comparison - see how SQL queries map to Rust Query Builder
# SQL verification - verify exact SQL equivalence (17 tests)
# Documentation examples - verify all doc examples compile and run (10 tests)
# Clone-free operations - demonstrates performance optimization (v0.2.0+)
# Memory safety verification - proves 'static doesn't cause memory leaks
# Lazy evaluation - demonstrates deferred execution and early termination
# Container support - demonstrates querying various container types
# Custom Queryable - implement Queryable for custom containers (7 examples)
# Arc<RwLock<T>> HashMap - thread-safe shared data with all 17 lazy operations
# Macro helpers - reduce boilerplate with 12 helper macros (30% less code)
# Extension trait & derive macros - call .query() directly on containers (v0.5.0+)
Example: SQL Comparison
The sql_comparison example demonstrates how traditional SQL queries (like those in HSQLDB) translate to Rust Query Builder:
// SQL: SELECT * FROM employees WHERE department = 'Engineering';
let engineering = new
.where_
.all;
// SQL: SELECT AVG(salary) FROM employees WHERE age < 30;
let avg_salary = new
.where_
.avg;
// SQL: SELECT * FROM employees ORDER BY salary DESC LIMIT 5;
let top_5 = new
.order_by_float_desc
.into_iter
.take
.;
The example demonstrates 15 different SQL patterns including SELECT, WHERE, JOIN, GROUP BY, ORDER BY, aggregations, and subqueries.
Performance
The query builder uses:
- O(n) filtering operations
- O(n log n) sorting operations
- O(n + m) hash-based joins
- Zero-cost abstractions - compiled down to efficient iterators
- Clone-free by default - most operations work with references (v0.2.0+)
Performance Characteristics
| Operation | Complexity | Memory | Clone Required? |
|---|---|---|---|
where_ / all |
O(n) | Zero extra | ❌ No |
count |
O(n) | Zero extra | ❌ No |
select |
O(n) | Only field copies | ❌ No |
sum / avg |
O(n) | Zero extra | ❌ No |
limit / skip |
O(n) | Zero extra | ❌ No |
order_by* |
O(n log n) | Clones all items | ✅ Yes |
group_by |
O(n) | Clones all items | ✅ Yes |
| Joins | O(n + m) | Zero extra | ❌ No |
Example: Filtering 10,000 employees (1KB each)
- v0.1.0: ~5ms (cloned 10MB)
- v0.2.0: ~0.1ms (zero copy) - 50x faster!
Key-Paths
This library leverages the key-paths crate to provide type-safe field access. The Keypaths derive macro automatically generates accessor methods for your structs:
// Generated methods:
// - Product::id_r() -> KeyPaths<Product, u32>
// - Product::name_r() -> KeyPaths<Product, String>
// - Product::price_r() -> KeyPaths<Product, f64>
License
This project is licensed under either of:
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
at your option.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Acknowledgments
Built with rust-key-paths for type-safe field access.