rust-queries-builder 1.0.0

A powerful, type-safe query builder library for Rust that leverages key-paths for SQL-like operations on in-memory collections
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# Joins and Views Guide

## Quick Reference for JOIN and VIEW Operations on Locked Data

**Version**: 0.8.0  
**Module**: `rust_queries_builder`

---

## Table of Contents

1. [JOINs]#joins
2. [Materialized Views]#materialized-views
3. [Complete Examples]#complete-examples
4. [SQL Comparisons]#sql-comparisons
5. [Performance Tips]#performance-tips

---

## JOINs

### 1. INNER JOIN

Returns only matching pairs from both collections.

```rust
use rust_queries_builder::LockJoinQuery;

let user_locks: Vec<_> = users.values().collect();
let order_locks: Vec<_> = orders.values().collect();

let results = LockJoinQuery::new(user_locks, order_locks)
    .inner_join(
        User::id_r(),           // Left key
        Order::user_id_r(),     // Right key
        |user, order| {         // Mapper: what to return
            (user.name.clone(), order.total)
        }
    );

// SQL: SELECT u.name, o.total FROM users u
//      INNER JOIN orders o ON o.user_id = u.id;
```

**When to use:** You only want records that have matches in both collections.

---

### 2. LEFT JOIN

Returns all left items, with optional right matches.

```rust
let results = LockJoinQuery::new(user_locks, order_locks)
    .left_join(
        User::id_r(),
        Order::user_id_r(),
        |user, order_opt| {     // Note: Option<&Order>
            match order_opt {
                Some(order) => format!("{} has order {}", user.name, order.id),
                None => format!("{} has no orders", user.name),
            }
        }
    );

// SQL: SELECT u.name, o.id FROM users u
//      LEFT JOIN orders o ON o.user_id = u.id;
```

**When to use:** You want all left items, even those without right matches.

---

### 3. RIGHT JOIN

Returns all right items, with optional left matches.

```rust
let results = LockJoinQuery::new(user_locks, order_locks)
    .right_join(
        User::id_r(),
        Order::user_id_r(),
        |user_opt, order| {     // Note: Option<&User>
            match user_opt {
                Some(user) => format!("Order {} by {}", order.id, user.name),
                None => format!("Order {} by unknown", order.id),
            }
        }
    );

// SQL: SELECT o.id, u.name FROM users u
//      RIGHT JOIN orders o ON o.user_id = u.id;
```

**When to use:** You want all right items, even those without left matches.

---

### 4. CROSS JOIN

Returns all combinations (Cartesian product).

```rust
let results = LockJoinQuery::new(user_locks, product_locks)
    .cross_join(|user, product| {
        format!("{} × {}", user.name, product.name)
    });

// SQL: SELECT u.name, p.name FROM users u
//      CROSS JOIN products p;
```

**When to use:** You need all combinations of two collections. **Warning**: Output size is `n × m`.

---

## Materialized Views

### Creating a Materialized View

Cache expensive queries for instant repeated access.

```rust
use rust_queries_builder::MaterializedLockView;

let expensive_view = MaterializedLockView::new(|| {
    products
        .lock_query()
        .where_(Product::active_r(), |&a| a)
        .where_(Product::price_r(), |&p| p > 500.0)
        .order_by_float_desc(Product::rating_r())
        .limit(100)
});

// SQL: CREATE MATERIALIZED VIEW expensive_view AS
//      SELECT * FROM products 
//      WHERE active = true AND price > 500
//      ORDER BY rating DESC
//      LIMIT 100;
```

### Querying a Materialized View

```rust
// Instant queries (no locks!)
let count = expensive_view.count();         // 42 ns!
let data = expensive_view.get();            // &[Product]

// Iterate cached data
for product in expensive_view.get() {
    println!("{}", product.name);
}
```

### Refreshing a Materialized View

```rust
// Update the cached data
expensive_view.refresh();

// SQL: REFRESH MATERIALIZED VIEW expensive_view;
```

**When to refresh:**
- On a timer (every N seconds/minutes)
- On events (after data updates)
- On demand (user clicks "refresh")

---

## Complete Examples

### Example 1: E-Commerce User Orders

```rust
use rust_queries_builder::{LockJoinQuery, LockQueryable};
use key_paths_derive::Keypaths;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

#[derive(Clone, Keypaths)]
struct User {
    id: u32,
    name: String,
    email: String,
}

#[derive(Clone, Keypaths)]
struct Order {
    id: u32,
    user_id: u32,
    total: f64,
}

fn main() {
    let mut users = HashMap::new();
    users.insert("u1".to_string(), Arc::new(RwLock::new(User {
        id: 1, name: "Alice".to_string(), email: "alice@example.com".to_string()
    })));

    let mut orders = HashMap::new();
    orders.insert("o1".to_string(), Arc::new(RwLock::new(Order {
        id: 101, user_id: 1, total: 99.99
    })));

    // INNER JOIN: Users with their orders
    let user_locks: Vec<_> = users.values().collect();
    let order_locks: Vec<_> = orders.values().collect();
    
    let user_orders = LockJoinQuery::new(user_locks, order_locks)
        .inner_join(
            User::id_r(),
            Order::user_id_r(),
            |user, order| {
                println!("{} ordered ${:.2}", user.name, order.total);
                (user.name.clone(), order.total)
            }
        );
    
    println!("Found {} user-order pairs", user_orders.len());
}
```

### Example 2: Analytics Dashboard with Materialized Views

```rust
use rust_queries_builder::{MaterializedLockView, LockQueryable};

fn create_analytics_views(
    products: &HashMap<String, Arc<RwLock<Product>>>,
) -> (MaterializedLockView<Product>, MaterializedLockView<Product>) {
    
    // View 1: Top selling products
    let products_clone1 = products.clone();
    let top_products = MaterializedLockView::new(move || {
        products_clone1
            .lock_query()
            .order_by_float_desc(Product::sales_r())
            .limit(10)
    });
    
    // View 2: Low stock alerts
    let products_clone2 = products.clone();
    let low_stock = MaterializedLockView::new(move || {
        products_clone2
            .lock_query()
            .where_(Product::stock_r(), |&s| s < 10)
            .order_by(Product::stock_r())
            .limit(50)
    });
    
    (top_products, low_stock)
}

fn main() {
    let products: HashMap<String, Arc<RwLock<Product>>> = /* ... */;
    let (mut top_view, mut low_stock_view) = create_analytics_views(&products);
    
    // Query views (instant!)
    println!("Top products: {}", top_view.count());
    println!("Low stock alerts: {}", low_stock_view.count());
    
    // Refresh every hour
    loop {
        std::thread::sleep(std::time::Duration::from_secs(3600));
        top_view.refresh();
        low_stock_view.refresh();
        println!("Views refreshed!");
    }
}
```

### Example 3: Complex Multi-table Join

```rust
// Active users with high-value orders and premium products
fn complex_join(
    users: &HashMap<String, Arc<RwLock<User>>>,
    orders: &HashMap<String, Arc<RwLock<Order>>>,
) -> Vec<(String, f64)> {
    
    // Step 1: Filter active users
    let active_users = users
        .lock_query()
        .where_(User::status_r(), |s| s == "active")
        .all();
    
    let user_locks: Vec<_> = active_users
        .iter()
        .map(|u| Arc::new(RwLock::new(u.clone())))
        .collect::<Vec<_>>();
    
    // Step 2: Filter high-value orders
    let high_value_orders = orders
        .lock_query()
        .where_(Order::total_r(), |&t| t > 100.0)
        .all();
    
    let order_locks: Vec<_> = high_value_orders
        .iter()
        .map(|o| Arc::new(RwLock::new(o.clone())))
        .collect::<Vec<_>>();
    
    // Step 3: Join
    let user_lock_refs: Vec<_> = user_locks.iter().map(|arc| &**arc).collect();
    let order_lock_refs: Vec<_> = order_locks.iter().map(|arc| &**arc).collect();
    
    LockJoinQuery::new(user_lock_refs, order_lock_refs)
        .inner_join(
            User::id_r(),
            Order::user_id_r(),
            |user, order| (user.name.clone(), order.total)
        )
}
```

---

## SQL Comparisons

### INNER JOIN

```sql
-- SQL
SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON o.user_id = u.id;
```

```rust
// Rust
LockJoinQuery::new(user_locks, order_locks)
    .inner_join(
        User::id_r(),
        Order::user_id_r(),
        |user, order| (user.name.clone(), order.total)
    )
```

### LEFT JOIN with NULL handling

```sql
-- SQL
SELECT 
    u.name,
    COALESCE(o.id, 0) as order_id
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;
```

```rust
// Rust
LockJoinQuery::new(user_locks, order_locks)
    .left_join(
        User::id_r(),
        Order::user_id_r(),
        |user, order_opt| {
            let order_id = order_opt.map(|o| o.id).unwrap_or(0);
            (user.name.clone(), order_id)
        }
    )
```

### JOIN with WHERE

```sql
-- SQL
SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON o.user_id = u.id
WHERE u.status = 'active'
AND o.total > 100;
```

```rust
// Rust
let active_users = users
    .lock_query()
    .where_(User::status_r(), |s| s == "active")
    .all();

let high_orders = orders
    .lock_query()
    .where_(Order::total_r(), |&t| t > 100.0)
    .all();

// Convert to locks and join...
```

### Materialized View

```sql
-- SQL
CREATE MATERIALIZED VIEW active_products AS
SELECT * FROM products 
WHERE active = true AND stock > 0
ORDER BY rating DESC;

-- Query
SELECT COUNT(*) FROM active_products;

-- Refresh
REFRESH MATERIALIZED VIEW active_products;
```

```rust
// Rust
let mut view = MaterializedLockView::new(|| {
    products
        .lock_query()
        .where_(Product::active_r(), |&a| a)
        .where_(Product::stock_r(), |&s| s > 0)
        .order_by_float_desc(Product::rating_r())
        .all()
});

// Query
let count = view.count();

// Refresh
view.refresh();
```

---

## Performance Tips

### 1. Pre-filter Before Joins

```rust
// ❌ Bad: Join everything first
let all_results = LockJoinQuery::new(all_users, all_orders)
    .inner_join(/* ... */);
let filtered: Vec<_> = all_results.into_iter()
    .filter(|(name, total)| total > 100.0)
    .collect();

// ✅ Good: Filter before joining
let expensive_orders = orders
    .lock_query()
    .where_(Order::total_r(), |&t| t > 100.0)
    .all();

let results = LockJoinQuery::new(users, expensive_orders)
    .inner_join(/* ... */);
```

### 2. Use Materialized Views for Repeated Queries

```rust
// ❌ Bad: Query every time (acquires locks)
for _ in 0..1000 {
    let count = products
        .lock_query()
        .where_(Product::active_r(), |&a| a)
        .count();  // 1000 lock acquisitions!
}

// ✅ Good: Query cached view
let view = MaterializedLockView::new(|| {
    products.lock_query()
        .where_(Product::active_r(), |&a| a)
        .all()
});

for _ in 0..1000 {
    let count = view.count();  // Instant! No locks!
}
```

### 3. Limit CROSS JOIN Size

```rust
// ❌ Bad: Huge cartesian product
let all_combos = LockJoinQuery::new(1000_items, 1000_items)
    .cross_join(/* ... */);  // 1,000,000 results!

// ✅ Good: Limit inputs first
let top_users = users.lock_query().limit(10).all();
let top_products = products.lock_query().limit(10).all();

let combos = LockJoinQuery::new(top_users, top_products)
    .cross_join(/* ... */);  // 100 results
```

### 4. Refresh Views Strategically

```rust
// ❌ Bad: Refresh on every read
fn get_view_data(view: &mut MaterializedLockView<Product>) -> usize {
    view.refresh();  // Expensive!
    view.count()
}

// ✅ Good: Refresh on timer
fn refresh_periodically(view: &mut MaterializedLockView<Product>) {
    let mut last_refresh = Instant::now();
    
    loop {
        if last_refresh.elapsed() > Duration::from_secs(60) {
            view.refresh();
            last_refresh = Instant::now();
        }
        std::thread::sleep(Duration::from_secs(1));
    }
}
```

### 5. Use Lazy Queries When Possible

```rust
// ❌ Bad: Eager join of large collections
let all_results = LockJoinQuery::new(huge_users, huge_orders)
    .inner_join(/* ... */);
let first_10 = &all_results[..10];  // Computed all results!

// ✅ Good: Use lazy + take
let first_10 = users
    .lock_lazy_query()
    .where_(User::active_r(), |&a| a)
    .take_lazy(10)
    .collect();  // Stops after 10 matches!
```

---

## Type Requirements

### JOIN Key Requirements

Keys must implement:
- `Clone` - To extract from locked values
- `Eq` - For equality comparison
- `PartialEq<RK>` - For cross-type comparison (left key == right key)

```rust
// Example: Join on different key types
#[derive(Clone, Eq, PartialEq)]
struct UserId(u32);

#[derive(Clone, Eq, PartialEq)]
struct OrderUserId(u32);

// Need PartialEq between types
impl PartialEq<OrderUserId> for UserId {
    fn eq(&self, other: &OrderUserId) -> bool {
        self.0 == other.0
    }
}
```

### Value Requirements

Values must implement:
- `Clone` - For extracting from locks (in current implementation)
- `'static` lifetime - For key-paths

---

## Common Patterns

### Pattern 1: User-Order-Product Chain

```rust
// Step 1: Users with orders
let user_orders = LockJoinQuery::new(user_locks, order_locks)
    .inner_join(User::id_r(), Order::user_id_r(), |u, o| {
        (u.name.clone(), o.product_id, o.total)
    });

// Step 2: Aggregate by product
let mut product_sales: HashMap<u32, f64> = HashMap::new();
for (_name, product_id, total) in user_orders {
    *product_sales.entry(product_id).or_insert(0.0) += total;
}

println!("Sales by product: {:?}", product_sales);
```

### Pattern 2: Subquery with Materialized View

```rust
// Subquery: Get IDs
let subquery_view = MaterializedLockView::new(|| {
    orders
        .lock_query()
        .where_(Order::status_r(), |s| s == "completed")
        .select(Order::user_id_r())
});

// Main query: Filter by IDs
let active_buyers = users
    .lock_query()
    .where_(User::id_r(), |id| subquery_view.get().contains(id))
    .all();
```

### Pattern 3: Multiple Views for Dashboard

```rust
struct Dashboard {
    top_products: MaterializedLockView<Product>,
    low_stock: MaterializedLockView<Product>,
    recent_orders: MaterializedLockView<Order>,
}

impl Dashboard {
    fn new(
        products: &HashMap<String, Arc<RwLock<Product>>>,
        orders: &HashMap<String, Arc<RwLock<Order>>>,
    ) -> Self {
        let p1 = products.clone();
        let p2 = products.clone();
        let o = orders.clone();
        
        Self {
            top_products: MaterializedLockView::new(move || {
                p1.lock_query().order_by_float_desc(Product::sales_r()).limit(10)
            }),
            low_stock: MaterializedLockView::new(move || {
                p2.lock_query().where_(Product::stock_r(), |&s| s < 10).all()
            }),
            recent_orders: MaterializedLockView::new(move || {
                o.lock_query().order_by_desc(Order::created_at_r()).limit(50)
            }),
        }
    }
    
    fn refresh_all(&mut self) {
        self.top_products.refresh();
        self.low_stock.refresh();
        self.recent_orders.refresh();
    }
}
```

---

## Error Handling

### Lock Poisoning

Both `RwLock` and `Mutex` handle poisoned locks gracefully:

```rust
// If a lock is poisoned, with_value returns None
let result = lock.with_value(|val| val.clone());
match result {
    Some(val) => println!("Got value: {:?}", val),
    None => println!("Lock was poisoned"),
}
```

### Empty Results

```rust
// JOINs return empty Vec if no matches
let results = LockJoinQuery::new(empty_users, orders)
    .inner_join(/* ... */);

assert_eq!(results.len(), 0);  // Empty result set
```

---

## Summary

### JOINs
- ✅ INNER JOIN - matching pairs only
- ✅ LEFT JOIN - all left + optional right
- ✅ RIGHT JOIN - all right + optional left
- ✅ CROSS JOIN - all combinations

### Views
- ✅ Materialized views - cache expensive queries
- ✅ Instant queries - no lock acquisition
- ✅ Refresh capability - update cached data

### Performance
- ✅ Microsecond range for joins
- ✅ Sub-microsecond for view queries
- ✅ Zero unnecessary copying

### Type Safety
- ✅ Key-path based joins
- ✅ Compile-time field validation
- ✅ Type-safe mappers

---

**For more examples, see:**
- `examples/advanced_lock_sql.rs` - Comprehensive JOIN and VIEW demos
- `examples/sql_like_lock_queries.rs` - Basic SQL operations
- `ADVANCED_LOCK_SQL_SUMMARY.md` - Complete feature summary

**Version**: 0.8.0  
**Status**: Production Ready ✅