stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
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
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Comprehensive JOIN Tests
//!
//! Tests various JOIN operations with different tables

use stoolap::Database;

fn setup_comprehensive_tables(db: &Database) {
    // Create categories_ch table with parent-child structure
    db.execute(
        "CREATE TABLE categories_ch (
            id INTEGER,
            name TEXT,
            parent_id INTEGER
        )",
        (),
    )
    .expect("Failed to create categories_ch table");

    // Create products table
    db.execute(
        "CREATE TABLE products (
            id INTEGER,
            name TEXT,
            category_id INTEGER,
            price FLOAT,
            in_stock BOOLEAN
        )",
        (),
    )
    .expect("Failed to create products table");

    // Create customers table
    db.execute(
        "CREATE TABLE customers (
            id INTEGER,
            name TEXT,
            email TEXT,
            country TEXT
        )",
        (),
    )
    .expect("Failed to create customers table");

    // Create orders table (using TEXT for order_date since DATE type is stored as TIMESTAMP)
    db.execute(
        "CREATE TABLE orders (
            id INTEGER,
            customer_id INTEGER,
            order_date TEXT,
            total FLOAT
        )",
        (),
    )
    .expect("Failed to create orders table");

    // Create order_items table
    db.execute(
        "CREATE TABLE order_items (
            order_id INTEGER,
            product_id INTEGER,
            quantity INTEGER,
            price FLOAT
        )",
        (),
    )
    .expect("Failed to create order_items table");

    // Insert data into categories_ch - parent_id NULL for top-level categories
    db.execute(
        "INSERT INTO categories_ch (id, name, parent_id) VALUES (1, 'Electronics', NULL)",
        (),
    )
    .unwrap();
    db.execute(
        "INSERT INTO categories_ch (id, name, parent_id) VALUES (2, 'Computers', 1)",
        (),
    )
    .unwrap();
    db.execute(
        "INSERT INTO categories_ch (id, name, parent_id) VALUES (3, 'Phones', 1)",
        (),
    )
    .unwrap();
    db.execute(
        "INSERT INTO categories_ch (id, name, parent_id) VALUES (4, 'Accessories', 1)",
        (),
    )
    .unwrap();
    db.execute(
        "INSERT INTO categories_ch (id, name, parent_id) VALUES (5, 'Clothing', NULL)",
        (),
    )
    .unwrap();
    db.execute(
        "INSERT INTO categories_ch (id, name, parent_id) VALUES (6, 'Books', NULL)",
        (),
    )
    .unwrap();

    // Insert data into products
    db.execute(
        "INSERT INTO products (id, name, category_id, price, in_stock) VALUES
        (101, 'Laptop', 2, 1200.00, true),
        (102, 'Smartphone', 3, 800.00, true),
        (103, 'Tablet', 2, 500.00, true),
        (104, 'Headphones', 4, 150.00, true),
        (105, 'Monitor', 2, 300.00, false),
        (106, 'Keyboard', 4, 80.00, true),
        (107, 'T-shirt', 5, 25.00, true),
        (108, 'Programming Book', 6, 40.00, true)",
        (),
    )
    .expect("Failed to insert products");

    // Insert data into customers
    db.execute(
        "INSERT INTO customers (id, name, email, country) VALUES
        (1, 'Alice Smith', 'alice@example.com', 'USA'),
        (2, 'Bob Johnson', 'bob@example.com', 'Canada'),
        (3, 'Charlie Brown', 'charlie@example.com', 'UK'),
        (4, 'Diana Adams', 'diana@example.com', 'Australia')",
        (),
    )
    .expect("Failed to insert customers");

    // Insert data into orders - customer_id NULL for anonymous order
    db.execute("INSERT INTO orders (id, customer_id, order_date, total) VALUES (1001, 1, '2023-01-15', 1350.00)", ())
        .unwrap();
    db.execute("INSERT INTO orders (id, customer_id, order_date, total) VALUES (1002, 2, '2023-01-16', 800.00)", ())
        .unwrap();
    db.execute("INSERT INTO orders (id, customer_id, order_date, total) VALUES (1003, 1, '2023-02-10', 45.00)", ())
        .unwrap();
    db.execute("INSERT INTO orders (id, customer_id, order_date, total) VALUES (1004, 3, '2023-02-20', 1200.00)", ())
        .unwrap();
    db.execute("INSERT INTO orders (id, customer_id, order_date, total) VALUES (1005, NULL, '2023-03-05', 40.00)", ())
        .unwrap();

    // Insert data into order_items
    db.execute(
        "INSERT INTO order_items (order_id, product_id, quantity, price) VALUES
        (1001, 101, 1, 1200.00),
        (1001, 104, 1, 150.00),
        (1002, 102, 1, 800.00),
        (1003, 107, 1, 25.00),
        (1004, 101, 1, 1200.00),
        (1005, 108, 1, 40.00)",
        (),
    )
    .expect("Failed to insert order_items");
}

/// Test self-join for parent-child category relationships
#[test]
fn test_category_self_join() {
    let db = Database::open("memory://join_self").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    // Run a self-join to get parent category names
    let result = db
        .query(
            "SELECT c.id, c.name, c.parent_id, p.name AS parent_name
             FROM categories_ch c
             LEFT JOIN categories_ch p ON c.parent_id = p.id
             ORDER BY c.id",
            (),
        )
        .expect("Failed to execute self JOIN");

    let mut categories_with_parent = 0;
    let mut total_categories = 0;

    for row in result {
        let row = row.expect("Failed to get row");
        let id: i64 = row.get(0).unwrap();
        let name: String = row.get(1).unwrap();
        let parent_name: Option<String> = row.get(3).unwrap();

        total_categories += 1;

        if parent_name.is_some() {
            categories_with_parent += 1;
            println!("Category {}: {} has parent {:?}", id, name, parent_name);
        } else {
            println!("Category {}: {} is a top-level category", id, name);
        }
    }

    assert_eq!(total_categories, 6, "Expected 6 total categories");
    assert_eq!(
        categories_with_parent, 3,
        "Expected 3 categories with parents"
    );
}

/// Test INNER JOIN between products and categories
#[test]
fn test_inner_join_products_categories() {
    let db = Database::open("memory://join_inner").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    // Query for in-stock products with their categories
    let result = db
        .query(
            "SELECT p.id, p.name, p.price, c.name AS category
             FROM products p
             INNER JOIN categories_ch c ON p.category_id = c.id
             WHERE p.in_stock = true
             ORDER BY p.price DESC",
            (),
        )
        .expect("Failed to execute INNER JOIN");

    let mut count = 0;
    for row in result {
        let row = row.expect("Failed to get row");
        let id: i64 = row.get(0).unwrap();
        let name: String = row.get(1).unwrap();
        let price: f64 = row.get(2).unwrap();
        let category: String = row.get(3).unwrap();

        println!(
            "Product: {} - {} (${}) in category {}",
            id, name, price, category
        );
        count += 1;
    }

    assert_eq!(count, 7, "Expected 7 in-stock products");
}

/// Test LEFT JOIN between orders and customers
#[test]
fn test_left_join_orders_customers() {
    let db = Database::open("memory://join_left").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    // Run LEFT JOIN to get all orders with customer names where available
    let result = db
        .query(
            "SELECT o.id, o.order_date, o.total, c.name AS customer_name
             FROM orders o
             LEFT JOIN customers c ON o.customer_id = c.id
             ORDER BY o.id",
            (),
        )
        .expect("Failed to execute LEFT JOIN");

    let mut total_orders = 0;
    let mut orders_with_null_customer = 0;

    for row in result {
        let row = row.expect("Failed to get row");
        let id: i64 = row.get(0).unwrap();
        let order_date: String = row.get(1).unwrap();
        let total: f64 = row.get(2).unwrap();
        let customer_name: Option<String> = row.get(3).unwrap();

        total_orders += 1;

        if customer_name.is_none() {
            orders_with_null_customer += 1;
            println!(
                "Order {} on {} for ${} has no customer",
                id, order_date, total
            );
        } else {
            println!(
                "Order {} on {} for ${} by {:?}",
                id, order_date, total, customer_name
            );
        }
    }

    assert_eq!(total_orders, 5, "Expected 5 total orders");
    assert_eq!(
        orders_with_null_customer, 1,
        "Expected 1 order with NULL customer"
    );
}

/// Test JOIN with ordering by category and price
#[test]
fn test_ordered_products_by_category() {
    let db = Database::open("memory://join_ordered").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    // Run a JOIN with ordering by category and then by price
    let result = db
        .query(
            "SELECT c.name AS category, p.name AS product, p.price
             FROM categories_ch c
             JOIN products p ON c.id = p.category_id
             ORDER BY c.name, p.price DESC",
            (),
        )
        .expect("Failed to execute JOIN with ordering");

    let mut unique_categories: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut products_found = 0;

    for row in result {
        let row = row.expect("Failed to get row");
        let category: String = row.get(0).unwrap();
        let product: String = row.get(1).unwrap();
        let price: f64 = row.get(2).unwrap();

        unique_categories.insert(category.clone());
        products_found += 1;
        println!(
            "Category: {} - Product: {} (${:.2})",
            category, product, price
        );
    }

    assert_eq!(
        unique_categories.len(),
        5,
        "Expected 5 categories with products"
    );
    assert_eq!(products_found, 8, "Expected 8 products");
}

/// Test three-way JOIN (orders -> order_items -> products)
#[test]
fn test_three_way_join() {
    let db = Database::open("memory://join_three").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    let result = db
        .query(
            "SELECT o.id AS order_id, p.name AS product_name, oi.quantity, oi.price
             FROM orders o
             JOIN order_items oi ON o.id = oi.order_id
             JOIN products p ON oi.product_id = p.id
             ORDER BY o.id, p.name",
            (),
        )
        .expect("Failed to execute three-way JOIN");

    let mut count = 0;
    for row in result {
        let row = row.expect("Failed to get row");
        let order_id: i64 = row.get(0).unwrap();
        let product_name: String = row.get(1).unwrap();
        let quantity: i64 = row.get(2).unwrap();
        let price: f64 = row.get(3).unwrap();

        println!(
            "Order {}: {} x{} @ ${:.2}",
            order_id, product_name, quantity, price
        );
        count += 1;
    }

    assert_eq!(count, 6, "Expected 6 order items");
}

/// Test JOIN with aggregation
#[test]
fn test_join_with_aggregation() {
    let db = Database::open("memory://join_agg").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    let result = db
        .query(
            "SELECT c.name, COUNT(*) AS product_count, AVG(p.price) AS avg_price
             FROM categories_ch c
             JOIN products p ON c.id = p.category_id
             GROUP BY c.name
             ORDER BY c.name",
            (),
        )
        .expect("Failed to execute JOIN with aggregation");

    let mut count = 0;
    for row in result {
        let row = row.expect("Failed to get row");
        let category: String = row.get(0).unwrap();
        let product_count: i64 = row.get(1).unwrap();
        let avg_price: f64 = row.get(2).unwrap();

        println!(
            "Category: {} - {} products, avg price ${:.2}",
            category, product_count, avg_price
        );
        count += 1;
    }

    assert!(count >= 5, "Expected at least 5 categories with products");
}

/// Test JOIN with WHERE clause on joined table
#[test]
fn test_join_with_where_on_joined() {
    let db = Database::open("memory://join_where").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    // Get orders from USA customers only
    let result = db
        .query(
            "SELECT o.id, o.total, c.name, c.country
             FROM orders o
             JOIN customers c ON o.customer_id = c.id
             WHERE c.country = 'USA'
             ORDER BY o.id",
            (),
        )
        .expect("Failed to execute JOIN with WHERE");

    let mut count = 0;
    for row in result {
        let row = row.expect("Failed to get row");
        let order_id: i64 = row.get(0).unwrap();
        let total: f64 = row.get(1).unwrap();
        let customer: String = row.get(2).unwrap();
        let country: String = row.get(3).unwrap();

        assert_eq!(country, "USA");
        println!(
            "Order {}: ${:.2} by {} ({})",
            order_id, total, customer, country
        );
        count += 1;
    }

    // Alice has 2 orders
    assert_eq!(count, 2, "Expected 2 orders from USA");
}

/// Test multiple JOINs with different types
#[test]
fn test_multiple_join_types() {
    let db = Database::open("memory://join_multi_type").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    // Complex query with both INNER and LEFT JOIN
    let result = db
        .query(
            "SELECT o.id AS order_id, c.name AS customer, p.name AS product
             FROM orders o
             LEFT JOIN customers c ON o.customer_id = c.id
             JOIN order_items oi ON o.id = oi.order_id
             JOIN products p ON oi.product_id = p.id
             ORDER BY o.id",
            (),
        )
        .expect("Failed to execute mixed JOINs");

    let mut null_customer_order_found = false;
    let mut count = 0;

    for row in result {
        let row = row.expect("Failed to get row");
        let order_id: i64 = row.get(0).unwrap();
        let customer: Option<String> = row.get(1).unwrap();
        let product: String = row.get(2).unwrap();

        if customer.is_none() {
            null_customer_order_found = true;
        }

        println!("Order {}: {:?} bought {}", order_id, customer, product);
        count += 1;
    }

    assert!(
        null_customer_order_found,
        "Expected to find an order with NULL customer"
    );
    assert_eq!(count, 6, "Expected 6 total order items");
}

/// Test RIGHT JOIN (if supported)
#[test]
fn test_right_join() {
    let db = Database::open("memory://join_right").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    // RIGHT JOIN to get all customers even without orders
    // Note: Some databases implement RIGHT JOIN differently
    let result = db.query(
        "SELECT c.name, o.id AS order_id
         FROM orders o
         RIGHT JOIN customers c ON o.customer_id = c.id
         ORDER BY c.name",
        (),
    );

    match result {
        Ok(rows) => {
            let mut count = 0;
            let mut customer_without_orders = false;

            for row in rows {
                let row = row.expect("Failed to get row");
                let name: String = row.get(0).unwrap();
                let order_id: Option<i64> = row.get(1).unwrap();

                if order_id.is_none() {
                    customer_without_orders = true;
                }

                println!("Customer: {} - Order: {:?}", name, order_id);
                count += 1;
            }

            // Diana has no orders
            assert!(
                customer_without_orders,
                "Expected to find customer without orders (Diana)"
            );
            assert!(count >= 4, "Expected at least 4 rows");
        }
        Err(_) => {
            // RIGHT JOIN might not be implemented
            println!("RIGHT JOIN not supported, skipping test");
        }
    }
}

/// Test JOIN with DISTINCT
#[test]
fn test_join_with_distinct() {
    let db = Database::open("memory://join_distinct").expect("Failed to create database");
    setup_comprehensive_tables(&db);

    // Get distinct customers who have placed orders
    let result = db
        .query(
            "SELECT DISTINCT c.name
             FROM customers c
             JOIN orders o ON c.id = o.customer_id
             ORDER BY c.name",
            (),
        )
        .expect("Failed to execute JOIN with DISTINCT");

    let mut customers: Vec<String> = Vec::new();
    for row in result {
        let row = row.expect("Failed to get row");
        let name: String = row.get(0).unwrap();
        customers.push(name);
    }

    // Alice, Bob, Charlie have orders (Diana does not)
    assert_eq!(
        customers.len(),
        3,
        "Expected 3 distinct customers with orders"
    );
    assert!(customers.contains(&"Alice Smith".to_string()));
    assert!(customers.contains(&"Bob Johnson".to_string()));
    assert!(customers.contains(&"Charlie Brown".to_string()));
}