ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
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
//! Database Performance Test
//!
//! This example tests actual database performance by:
//! - Creating realistic test data (10K+ records)
//! - Executing complex queries with JOINs and aggregations
//! - Measuring query execution time vs SQL generation time
//! - Testing index effectiveness
//! - Comparing different query patterns

use anyhow::Result;
use chrono::{DateTime, Utc};
use ignis_db::{index, table, view, Deletable, IgnisModel, Insertable, Query, Source, Updatable};
use sqlx::{PgPool, Row};
use std::time::Instant;

// Define test schema with realistic data
table! {
    users (id) {
        id -> Int4,
        email -> Varchar,
        name -> Text,
        department_id -> Int4,
        salary -> Numeric,
        created_at -> Timestamptz,
        last_login -> Timestamptz,
        is_active -> Bool,
    }
}

table! {
    departments (id) {
        id -> Int4,
        name -> Varchar,
        budget -> Numeric,
        created_at -> Timestamptz,
    }
}

table! {
    projects (id) {
        id -> Int4,
        name -> Varchar,
        department_id -> Int4,
        status -> Varchar,
        start_date -> Timestamptz,
        end_date -> Timestamptz,
        budget -> Numeric,
        created_at -> Timestamptz,
    }
}

table! {
    user_projects (id) {
        id -> Int4,
        user_id -> Int4,
        project_id -> Int4,
        role -> Varchar,
        hours_allocated -> Numeric,
        hourly_rate -> Numeric,
        joined_at -> Timestamptz,
    }
}

table! {
    time_logs (id) {
        id -> Int4,
        user_id -> Int4,
        project_id -> Int4,
        date -> Timestamptz,
        hours_worked -> Numeric,
        description -> Text,
        created_at -> Timestamptz,
    }
}

view! {
    user_performance (id) {
        id -> Int4,
        name -> Varchar,
        department -> Varchar,
        total_hours -> Numeric,
        total_earnings -> Numeric,
        project_count -> Int4,
        avg_hourly_rate -> Numeric,
    }
}

// Create indexes for performance testing
index!(idx_users_email(users, email));
index!(idx_users_department(users, department_id));
index!(idx_users_active(users, is_active));
index!(idx_projects_department(projects, department_id));
index!(idx_projects_status(projects, status));
index!(idx_user_projects_user(user_projects, user_id));
index!(idx_user_projects_project(user_projects, project_id));
index!(idx_time_logs_user_date(time_logs, user_id, date));
index!(idx_time_logs_project(time_logs, project_id));

#[derive(Debug, Clone)]
struct User {
    pub id: i32,
    pub email: String,
    pub name: String,
    pub department_id: i32,
    pub salary: rust_decimal::Decimal,
    pub created_at: DateTime<Utc>,
    pub last_login: DateTime<Utc>,
    pub is_active: bool,
}

#[derive(Debug, Clone)]
struct Department {
    pub id: i32,
    pub name: String,
    pub budget: rust_decimal::Decimal,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone)]
struct Project {
    pub id: i32,
    pub name: String,
    pub department_id: i32,
    pub status: String,
    pub start_date: DateTime<Utc>,
    pub end_date: DateTime<Utc>,
    pub budget: rust_decimal::Decimal,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone)]
struct UserProject {
    pub id: i32,
    pub user_id: i32,
    pub project_id: i32,
    pub role: String,
    pub hours_allocated: rust_decimal::Decimal,
    pub hourly_rate: rust_decimal::Decimal,
    pub joined_at: DateTime<Utc>,
}

#[derive(Debug, Clone)]
struct TimeLog {
    pub id: i32,
    pub user_id: i32,
    pub project_id: i32,
    pub date: DateTime<Utc>,
    pub hours_worked: rust_decimal::Decimal,
    pub description: String,
    pub created_at: DateTime<Utc>,
}

async fn setup_test_database(pool: &PgPool) -> Result<()> {
    println!("🔄 Setting up test database...");

    // Clean up existing data
    sqlx::query("DROP TABLE IF EXISTS time_logs CASCADE")
        .execute(pool)
        .await?;
    sqlx::query("DROP TABLE IF EXISTS user_projects CASCADE")
        .execute(pool)
        .await?;
    sqlx::query("DROP TABLE IF EXISTS projects CASCADE")
        .execute(pool)
        .await?;
    sqlx::query("DROP TABLE IF EXISTS users CASCADE")
        .execute(pool)
        .await?;
    sqlx::query("DROP TABLE IF EXISTS departments CASCADE")
        .execute(pool)
        .await?;

    // Create tables
    sqlx::query(&departments::table().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&users::table().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&projects::table().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&user_projects::table().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&time_logs::table().generate_ddl())
        .execute(pool)
        .await?;

    // Create indexes
    sqlx::query(&idx_users_email::meta().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&idx_users_department::meta().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&idx_users_active::meta().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&idx_projects_department::meta().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&idx_projects_status::meta().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&idx_user_projects_user::meta().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&idx_user_projects_project::meta().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&idx_time_logs_user_date::meta().generate_ddl())
        .execute(pool)
        .await?;
    sqlx::query(&idx_time_logs_project::meta().generate_ddl())
        .execute(pool)
        .await?;

    println!("✅ Database setup complete");
    Ok(())
}

async fn generate_test_data(pool: &PgPool) -> Result<()> {
    println!("🔄 Generating test data...");

    // Generate departments
    let dept_names = vec![
        "Engineering",
        "Marketing",
        "Sales",
        "Finance",
        "HR",
        "Operations",
    ];
    for (i, name) in dept_names.iter().enumerate() {
        sqlx::query(
            "INSERT INTO departments (id, name, budget, created_at) VALUES ($1, $2, $3, $4)",
        )
        .bind(i as i32 + 1)
        .bind(name)
        .bind(rust_decimal::Decimal::new(1000000, 0)) // $1M budget
        .bind(Utc::now())
        .execute(pool)
        .await?;
    }

    // Generate users (10,000)
    println!("   Generating 10,000 users...");
    for i in 1..=10000 {
        let dept_id = (i % 6) + 1;
        let salary = rust_decimal::Decimal::new(50000 + (i % 100000), 0);
        let is_active = i % 10 != 0; // 90% active users

        sqlx::query("INSERT INTO users (id, email, name, department_id, salary, created_at, last_login, is_active) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)")
            .bind(i)
            .bind(format!("user{}@company.com", i))
            .bind(format!("User {}", i))
            .bind(dept_id)
            .bind(salary)
            .bind(Utc::now())
            .bind(Utc::now())
            .bind(is_active)
            .execute(pool).await?;
    }

    // Generate projects (1,000)
    println!("   Generating 1,000 projects...");
    for i in 1..=1000 {
        let dept_id = (i % 6) + 1;
        let status = if i % 4 == 0 {
            "completed"
        } else if i % 4 == 1 {
            "active"
        } else {
            "planning"
        };

        sqlx::query("INSERT INTO projects (id, name, department_id, status, start_date, end_date, budget, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)")
            .bind(i)
            .bind(format!("Project {}", i))
            .bind(dept_id)
            .bind(status)
            .bind(Utc::now())
            .bind(Utc::now())
            .bind(rust_decimal::Decimal::new(100000 + (i % 900000), 0))
            .bind(Utc::now())
            .execute(pool).await?;
    }

    // Generate user-project assignments (50,000)
    println!("   Generating 50,000 user-project assignments...");
    for i in 1..=50000 {
        let user_id = (i % 10000) + 1;
        let project_id = (i % 1000) + 1;
        let role = if i % 3 == 0 {
            "developer"
        } else if i % 3 == 1 {
            "designer"
        } else {
            "manager"
        };
        let hours = rust_decimal::Decimal::new(20 + (i % 40), 0);
        let rate = rust_decimal::Decimal::new(25 + (i % 75), 0);

        sqlx::query("INSERT INTO user_projects (id, user_id, project_id, role, hours_allocated, hourly_rate, joined_at) VALUES ($1, $2, $3, $4, $5, $6, $7)")
            .bind(i)
            .bind(user_id)
            .bind(project_id)
            .bind(role)
            .bind(hours)
            .bind(rate)
            .bind(Utc::now())
            .execute(pool).await?;
    }

    // Generate time logs (100,000)
    println!("   Generating 100,000 time logs...");
    for i in 1..=100000 {
        let user_id = (i % 10000) + 1;
        let project_id = (i % 1000) + 1;
        let hours = rust_decimal::Decimal::new(1 + (i % 8), 0);

        sqlx::query("INSERT INTO time_logs (id, user_id, project_id, date, hours_worked, description, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7)")
            .bind(i)
            .bind(user_id)
            .bind(project_id)
            .bind(Utc::now())
            .bind(hours)
            .bind(format!("Work on project {}", project_id))
            .bind(Utc::now())
            .execute(pool).await?;
    }

    println!("✅ Test data generation complete");
    Ok(())
}

async fn run_performance_tests(pool: &PgPool) -> Result<()> {
    println!("\n🚀 Running Performance Tests");
    println!("{}", "=".repeat(60));

    // Test 1: Simple SELECT with WHERE
    println!("\n📊 Test 1: Simple SELECT with WHERE");
    println!("{}", "-".repeat(40));

    let query = Query::new()
        .from_table(users::table())
        .select_columns(vec![
            "id".to_string(),
            "name".to_string(),
            "email".to_string(),
        ])
        .filter("is_active = true AND department_id = 1")
        .limit(100);

    let sql = query.to_sql();
    println!("Generated SQL: {}", sql);

    // Measure SQL generation time
    let start = Instant::now();
    for _ in 0..1000 {
        let _sql = query.to_sql();
    }
    let sql_gen_time = start.elapsed();

    // Measure actual query execution time
    let start = Instant::now();
    let rows = sqlx::query(&sql).fetch_all(pool).await?;
    let query_exec_time = start.elapsed();

    println!("✅ SQL Generation (1000x): {:?}", sql_gen_time);
    println!("✅ Query Execution: {:?}", query_exec_time);
    println!("✅ Rows returned: {}", rows.len());

    // Test 2: Complex JOIN with aggregation
    println!("\n📊 Test 2: Complex JOIN with Aggregation");
    println!("{}", "-".repeat(40));

    let query = Query::new()
        .from_table(users::table())
        .inner_join_table(departments::table(), "users.department_id = departments.id")
        .inner_join_table(user_projects::table(), "users.id = user_projects.user_id")
        .select_columns(vec![
            "departments.name".to_string(),
            "COUNT(DISTINCT users.id)".to_string(),
            "AVG(user_projects.hourly_rate)".to_string(),
            "SUM(user_projects.hours_allocated)".to_string(),
        ])
        .filter("users.is_active = true")
        .group_by("departments.name")
        .having("COUNT(DISTINCT users.id) > 100")
        .order_by("COUNT(DISTINCT users.id) DESC");

    let sql = query.to_sql();
    println!("Generated SQL: {}", sql);

    // Measure SQL generation time
    let start = Instant::now();
    for _ in 0..1000 {
        let _sql = query.to_sql();
    }
    let sql_gen_time = start.elapsed();

    // Measure actual query execution time
    let start = Instant::now();
    let rows = sqlx::query(&sql).fetch_all(pool).await?;
    let query_exec_time = start.elapsed();

    println!("✅ SQL Generation (1000x): {:?}", sql_gen_time);
    println!("✅ Query Execution: {:?}", query_exec_time);
    println!("✅ Rows returned: {}", rows.len());

    // Test 3: Time-based analytics query
    println!("\n📊 Test 3: Time-based Analytics Query");
    println!("{}", "-".repeat(40));

    let query = Query::new()
        .from_table(time_logs::table())
        .inner_join_table(users::table(), "time_logs.user_id = users.id")
        .inner_join_table(projects::table(), "time_logs.project_id = projects.id")
        .select_columns(vec![
            "users.name".to_string(),
            "projects.name".to_string(),
            "SUM(time_logs.hours_worked)".to_string(),
            "COUNT(time_logs.id)".to_string(),
        ])
        .filter("time_logs.date >= NOW() - INTERVAL '30 days'")
        .group_by("users.name, projects.name")
        .having("SUM(time_logs.hours_worked) > 40")
        .order_by("SUM(time_logs.hours_worked) DESC")
        .limit(50);

    let sql = query.to_sql();
    println!("Generated SQL: {}", sql);

    // Measure SQL generation time
    let start = Instant::now();
    for _ in 0..1000 {
        let _sql = query.to_sql();
    }
    let sql_gen_time = start.elapsed();

    // Measure actual query execution time
    let start = Instant::now();
    let rows = sqlx::query(&sql).fetch_all(pool).await?;
    let query_exec_time = start.elapsed();

    println!("✅ SQL Generation (1000x): {:?}", sql_gen_time);
    println!("✅ Query Execution: {:?}", query_exec_time);
    println!("✅ Rows returned: {}", rows.len());

    // Test 4: Index effectiveness test
    println!("\n📊 Test 4: Index Effectiveness Test");
    println!("{}", "-".repeat(40));

    // Query without index hint
    let query_no_index = Query::new()
        .from_table(users::table())
        .select_columns(vec!["id".to_string(), "email".to_string()])
        .filter("email = 'user5000@company.com'");

    let sql_no_index = query_no_index.to_sql();

    // Query with index hint
    let query_with_index = Query::new()
        .from_table(users::table())
        .select_columns(vec!["id".to_string(), "email".to_string()])
        .filter("email = 'user5000@company.com'")
        .with_indexes(vec![idx_users_email::meta()]);

    let sql_with_index = query_with_index.to_sql();

    // Execute both and compare
    let start = Instant::now();
    let rows_no_index = sqlx::query(&sql_no_index).fetch_all(pool).await?;
    let time_no_index = start.elapsed();

    let start = Instant::now();
    let rows_with_index = sqlx::query(&sql_with_index).fetch_all(pool).await?;
    let time_with_index = start.elapsed();

    println!(
        "✅ Query without index hint: {:?} ({} rows)",
        time_no_index,
        rows_no_index.len()
    );
    println!(
        "✅ Query with index hint: {:?} ({} rows)",
        time_with_index,
        rows_with_index.len()
    );

    // Test 5: Bulk operations performance
    println!("\n📊 Test 5: Bulk Operations Performance");
    println!("{}", "-".repeat(40));

    // Bulk SELECT
    let start = Instant::now();
    let rows = sqlx::query("SELECT * FROM users WHERE department_id = 1 LIMIT 1000")
        .fetch_all(pool)
        .await?;
    let bulk_select_time = start.elapsed();
    println!(
        "✅ Bulk SELECT (1000 users): {:?} ({} rows)",
        bulk_select_time,
        rows.len()
    );

    // Bulk UPDATE
    let start = Instant::now();
    let result = sqlx::query("UPDATE users SET last_login = NOW() WHERE department_id = 1")
        .execute(pool)
        .await?;
    let bulk_update_time = start.elapsed();
    println!(
        "✅ Bulk UPDATE: {:?} ({} rows affected)",
        bulk_update_time,
        result.rows_affected()
    );

    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    println!("🚀 Database Performance Test");
    println!("{}", "=".repeat(60));

    let database_url = "postgresql://postgres:postgres@localhost:5433/postgres";
    match PgPool::connect(database_url).await {
        Ok(pool) => {
            println!("✅ Database connection successful!");

            // Setup and run tests
            setup_test_database(&pool).await?;
            generate_test_data(&pool).await?;
            run_performance_tests(&pool).await?;

            println!("\n🎉 Database performance test complete!");
            println!("\n📊 Summary of Performance Metrics:");
            println!("   • SQL Generation: Measured for 1000 iterations");
            println!("   • Query Execution: Real database queries");
            println!("   • Index Effectiveness: Before/after comparison");
            println!("   • Bulk Operations: Large dataset performance");
            println!("   • Data Volume: 10K users, 1K projects, 100K time logs");
        }
        Err(e) => {
            println!("❌ Failed to connect to database: {}", e);
            println!("💡 Make sure Docker PostgreSQL is running on port 5433");
        }
    }

    Ok(())
}