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
//! Custom SQL Migration Demo
//!
//! This example demonstrates how to use Ignis-DB's custom SQL migration system
//! to handle database patches and operations that the standard builders cannot accommodate.

use anyhow::Result;
use ignis_db::builders::*;

#[tokio::main]
async fn main() -> Result<()> {
    println!("🔧 Custom SQL Migration Demo");
    println!("============================");
    println!("Demonstrating custom SQL patches and database operations");
    println!();

    // ========== BASIC CUSTOM SQL MIGRATIONS ==========
    println!("📝 Creating Basic Custom SQL Migrations:");
    println!("=========================================");

    // Simple index creation
    let index_migration = custom_sql_with_id("001_add_performance_index")
        .name("Add performance index for user queries")
        .up_sql("CREATE INDEX CONCURRENTLY idx_users_email_performance ON users(email) WHERE status = 'active'")
        .down_sql("DROP INDEX IF EXISTS idx_users_email_performance")
        .description("Adds a partial index to improve query performance for active users")
        .tag("performance")
        .tag("index")
        .non_destructive()
        .rollback_safe()
        .build()?;

    println!("✅ Created index migration: {}", index_migration.name);

    // Data migration
    let data_migration = custom_sql_with_id("002_migrate_user_status")
        .name("Migrate user status values")
        .up_sql(
            r#"
            UPDATE users 
            SET status = CASE 
                WHEN status = 'enabled' THEN 'active'
                WHEN status = 'disabled' THEN 'inactive'
                ELSE status
            END
            WHERE status IN ('enabled', 'disabled')
        "#,
        )
        .down_sql(
            r#"
            UPDATE users 
            SET status = CASE 
                WHEN status = 'active' THEN 'enabled'
                WHEN status = 'inactive' THEN 'disabled'
                ELSE status
            END
            WHERE status IN ('active', 'inactive')
        "#,
        )
        .description("Migrates old status values to new standardized values")
        .tag("data-migration")
        .tag("status")
        .non_destructive()
        .rollback_safe()
        .build()?;

    println!("✅ Created data migration: {}", data_migration.name);

    // ========== ADVANCED CUSTOM SQL MIGRATIONS ==========
    println!("\n🔧 Creating Advanced Custom SQL Migrations:");
    println!("=============================================");

    // Complex schema patch
    let schema_patch = custom_sql_with_id("003_add_audit_columns")
        .name("Add audit columns to existing tables")
        .up_sql(
            r#"
            -- Add audit columns to users table
            ALTER TABLE users 
            ADD COLUMN created_at TIMESTAMPTZ DEFAULT NOW(),
            ADD COLUMN updated_at TIMESTAMPTZ DEFAULT NOW(),
            ADD COLUMN created_by UUID,
            ADD COLUMN updated_by UUID;
            
            -- Add audit columns to roles table
            ALTER TABLE roles 
            ADD COLUMN created_at TIMESTAMPTZ DEFAULT NOW(),
            ADD COLUMN updated_at TIMESTAMPTZ DEFAULT NOW(),
            ADD COLUMN created_by UUID,
            ADD COLUMN updated_by UUID;
            
            -- Create function to update updated_at timestamp
            CREATE OR REPLACE FUNCTION update_updated_at_column()
            RETURNS TRIGGER AS $$
            BEGIN
                NEW.updated_at = NOW();
                RETURN NEW;
            END;
            $$ language 'plpgsql';
            
            -- Create triggers for updated_at
            CREATE TRIGGER update_users_updated_at 
                BEFORE UPDATE ON users 
                FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
                
            CREATE TRIGGER update_roles_updated_at 
                BEFORE UPDATE ON roles 
                FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
        "#,
        )
        .down_sql(
            r#"
            -- Drop triggers
            DROP TRIGGER IF EXISTS update_users_updated_at ON users;
            DROP TRIGGER IF EXISTS update_roles_updated_at ON roles;
            
            -- Drop function
            DROP FUNCTION IF EXISTS update_updated_at_column();
            
            -- Remove audit columns
            ALTER TABLE users 
            DROP COLUMN IF EXISTS created_at,
            DROP COLUMN IF EXISTS updated_at,
            DROP COLUMN IF EXISTS created_by,
            DROP COLUMN IF EXISTS updated_by;
            
            ALTER TABLE roles 
            DROP COLUMN IF EXISTS created_at,
            DROP COLUMN IF EXISTS updated_at,
            DROP COLUMN IF EXISTS created_by,
            DROP COLUMN IF EXISTS updated_by;
        "#,
        )
        .description("Adds comprehensive audit trail to existing tables")
        .tag("schema-patch")
        .tag("audit")
        .tag("triggers")
        .non_destructive()
        .rollback_safe()
        .build()?;

    println!("✅ Created schema patch: {}", schema_patch.name);

    // Performance optimization
    let performance_migration = custom_sql_with_id("004_optimize_queries")
        .name("Optimize database queries and statistics")
        .up_sql(
            r#"
            -- Update table statistics
            ANALYZE users;
            ANALYZE roles;
            
            -- Create covering index for common query pattern
            CREATE INDEX CONCURRENTLY idx_users_tenant_status_email 
            ON users(tenant_id, status) 
            INCLUDE (email, name)
            WHERE status = 'active';
            
            -- Create partial index for admin queries
            CREATE INDEX CONCURRENTLY idx_users_admin_queries 
            ON users(created_at, status) 
            WHERE status IN ('active', 'inactive');
            
            -- Update query planner statistics
            UPDATE pg_stat_user_tables 
            SET n_tup_ins = 0, n_tup_upd = 0, n_tup_del = 0 
            WHERE relname IN ('users', 'roles');
        "#,
        )
        .down_sql(
            r#"
            -- Drop the indexes
            DROP INDEX IF EXISTS idx_users_tenant_status_email;
            DROP INDEX IF EXISTS idx_users_admin_queries;
        "#,
        )
        .description("Optimizes database performance with strategic indexes and statistics")
        .tag("performance")
        .tag("optimization")
        .tag("indexes")
        .non_destructive()
        .rollback_safe()
        .build()?;

    println!(
        "✅ Created performance migration: {}",
        performance_migration.name
    );

    // ========== DESTRUCTIVE MIGRATIONS ==========
    println!("\n⚠️  Creating Destructive Migrations:");
    println!("=====================================");

    // Destructive migration (requires manual review)
    let destructive_migration = custom_sql_with_id("005_remove_deprecated_columns")
        .name("Remove deprecated columns from users table")
        .up_sql(
            r#"
            -- Remove deprecated columns
            ALTER TABLE users 
            DROP COLUMN IF EXISTS old_status,
            DROP COLUMN IF EXISTS legacy_id,
            DROP COLUMN IF EXISTS deprecated_field;
            
            -- Remove unused index
            DROP INDEX IF EXISTS idx_users_old_status;
        "#,
        )
        .down_sql(
            r#"
            -- Note: This rollback cannot restore the dropped data
            -- This migration is not rollback-safe
            ALTER TABLE users 
            ADD COLUMN old_status VARCHAR(50),
            ADD COLUMN legacy_id INTEGER,
            ADD COLUMN deprecated_field TEXT;
            
            CREATE INDEX idx_users_old_status ON users(old_status);
        "#,
        )
        .description("Removes deprecated columns that are no longer used")
        .tag("destructive")
        .tag("cleanup")
        .destructive()
        .requires_manual_review()
        .not_rollback_safe()
        .build()?;

    println!(
        "✅ Created destructive migration: {}",
        destructive_migration.name
    );

    // ========== SECURITY PATCHES ==========
    println!("\n🔒 Creating Security Patches:");
    println!("==============================");

    // Security patch
    let security_patch = custom_sql_with_id("006_security_hardening")
        .name("Apply security hardening measures")
        .up_sql(
            r#"
            -- Revoke unnecessary permissions
            REVOKE ALL ON SCHEMA public FROM PUBLIC;
            GRANT USAGE ON SCHEMA public TO authenticated;
            GRANT CREATE ON SCHEMA public TO admin;
            
            -- Update RLS policies for better security
            DROP POLICY IF EXISTS users_select_policy ON users;
            CREATE POLICY users_select_policy ON users
                FOR SELECT TO authenticated
                USING (
                    tenant_id = current_setting('app.tenant_id')::uuid
                    AND status = 'active'
                );
            
            -- Add row-level security to sensitive tables
            ALTER TABLE users ENABLE ROW LEVEL SECURITY;
            ALTER TABLE roles ENABLE ROW LEVEL SECURITY;
            
            -- Create audit log table
            CREATE TABLE IF NOT EXISTS audit_log (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                table_name VARCHAR(255) NOT NULL,
                operation VARCHAR(10) NOT NULL,
                old_values JSONB,
                new_values JSONB,
                user_id UUID,
                timestamp TIMESTAMPTZ DEFAULT NOW()
            );
            
            -- Create audit trigger function
            CREATE OR REPLACE FUNCTION audit_trigger_function()
            RETURNS TRIGGER AS $$
            BEGIN
                INSERT INTO audit_log (table_name, operation, old_values, new_values, user_id)
                VALUES (
                    TG_TABLE_NAME,
                    TG_OP,
                    CASE WHEN TG_OP = 'DELETE' THEN to_jsonb(OLD) ELSE NULL END,
                    CASE WHEN TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN to_jsonb(NEW) ELSE NULL END,
                    current_setting('app.user_id', true)::uuid
                );
                RETURN COALESCE(NEW, OLD);
            END;
            $$ LANGUAGE plpgsql;
            
            -- Create audit triggers
            CREATE TRIGGER users_audit_trigger
                AFTER INSERT OR UPDATE OR DELETE ON users
                FOR EACH ROW EXECUTE FUNCTION audit_trigger_function();
        "#,
        )
        .down_sql(
            r#"
            -- Remove audit triggers
            DROP TRIGGER IF EXISTS users_audit_trigger ON users;
            
            -- Drop audit function
            DROP FUNCTION IF EXISTS audit_trigger_function();
            
            -- Drop audit log table
            DROP TABLE IF EXISTS audit_log;
            
            -- Restore original permissions (simplified)
            GRANT USAGE ON SCHEMA public TO PUBLIC;
        "#,
        )
        .description("Applies comprehensive security hardening measures")
        .tag("security")
        .tag("patch")
        .tag("audit")
        .non_destructive()
        .rollback_safe()
        .build()?;

    println!("✅ Created security patch: {}", security_patch.name);

    // ========== MIGRATION WITH DEPENDENCIES ==========
    println!("\n🔗 Creating Migration with Dependencies:");
    println!("========================================");

    // Migration that depends on others
    let dependent_migration = custom_sql_with_id("007_add_advanced_features")
        .name("Add advanced features that depend on previous migrations")
        .up_sql(
            r#"
            -- This migration depends on the audit columns and security patches
            CREATE TABLE user_sessions (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                user_id UUID NOT NULL REFERENCES users(id),
                session_token VARCHAR(255) NOT NULL UNIQUE,
                expires_at TIMESTAMPTZ NOT NULL,
                created_at TIMESTAMPTZ DEFAULT NOW(),
                updated_at TIMESTAMPTZ DEFAULT NOW(),
                created_by UUID,
                updated_by UUID
            );
            
            -- Add RLS policy for sessions
            ALTER TABLE user_sessions ENABLE ROW LEVEL SECURITY;
            CREATE POLICY user_sessions_policy ON user_sessions
                FOR ALL TO authenticated
                USING (user_id = current_setting('app.user_id')::uuid);
            
            -- Create index for session lookups
            CREATE INDEX idx_user_sessions_token ON user_sessions(session_token);
            CREATE INDEX idx_user_sessions_user_id ON user_sessions(user_id);
        "#,
        )
        .down_sql(
            r#"
            DROP TABLE IF EXISTS user_sessions;
        "#,
        )
        .description("Adds user session management with proper security")
        .tag("feature")
        .tag("sessions")
        .tag("security")
        .depends_on("003_add_audit_columns")
        .depends_on("006_security_hardening")
        .non_destructive()
        .rollback_safe()
        .build()?;

    println!(
        "✅ Created dependent migration: {}",
        dependent_migration.name
    );

    // ========== MIGRATION VALIDATION ==========
    println!("\n✅ Migration Validation:");
    println!("========================");

    let migrations = vec![
        &index_migration,
        &data_migration,
        &schema_patch,
        &performance_migration,
        &destructive_migration,
        &security_patch,
        &dependent_migration,
    ];

    let mut validation_errors = Vec::new();
    let mut total_migrations = 0;
    let mut destructive_count = 0;
    let mut review_required_count = 0;

    for migration in &migrations {
        total_migrations += 1;

        // Validate migration
        let validation_result = migration.validate();
        if !validation_result.is_valid {
            validation_errors.push(format!(
                "Migration {}: {}",
                migration.name,
                validation_result.errors.join(", ")
            ));
        }

        // Count special migration types
        if migration.name.contains("destructive") || migration.name.contains("remove") {
            destructive_count += 1;
        }
        if migration.name.contains("security") || migration.name.contains("hardening") {
            review_required_count += 1;
        }
    }

    println!("   - Total migrations created: {}", total_migrations);
    println!("   - Destructive migrations: {}", destructive_count);
    println!("   - Review required migrations: {}", review_required_count);
    println!("   - Validation errors: {}", validation_errors.len());

    if !validation_errors.is_empty() {
        println!("\n❌ Validation Errors:");
        for error in validation_errors {
            println!("   - {}", error);
        }
    } else {
        println!("\n✅ All migrations validated successfully!");
    }

    // ========== MIGRATION SUMMARY ==========
    println!("\n📊 Migration Summary:");
    println!("=====================");

    for migration in migrations {
        println!("   - {}: {}", migration.id, migration.name);
        println!("     Checksum: {}", migration.checksum);
        if let Some(ref down) = migration.down_sql {
            println!("     Rollback: Available ({} chars)", down.len());
        } else {
            println!("     Rollback: Not available");
        }
    }

    println!("\n🚀 Custom SQL Migration Demo Complete!");
    println!("=====================================");
    println!("Key Features Demonstrated:");
    println!("  ✅ Custom SQL patches for any database operation");
    println!("  ✅ Rollback support with down migrations");
    println!("  ✅ Migration validation and error checking");
    println!("  ✅ Destructive migration warnings");
    println!("  ✅ Dependency management between migrations");
    println!("  ✅ Tagging and categorization system");
    println!("  ✅ Manual review requirements for sensitive changes");
    println!("  ✅ Comprehensive audit and security patches");

    println!("\n💡 Usage in Production:");
    println!("  - Store migration files in version control");
    println!("  - Always test rollbacks in staging environment");
    println!("  - Review destructive migrations with team");
    println!("  - Use dependency management for complex changes");
    println!("  - Monitor migration execution and performance");

    Ok(())
}