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
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
use crate::schema::{
    CompositeField, CompositeType, Grant, Index, Role, StoredFunction, StoredProcedure, Table,
    Trigger, View,
};
use anyhow::Result;
use sqlx::{PgPool, Row};
use std::collections::HashMap;

/// Database introspection engine for reading existing PostgreSQL schema
pub struct DatabaseIntrospector {
    pool: PgPool,
}

impl DatabaseIntrospector {
    /// Create a new introspector with a database connection pool
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    /// Introspect all tables from information_schema
    pub async fn introspect_tables(&self) -> Result<Vec<Table>> {
        let query = r#"
            SELECT 
                t.table_name,
                c.column_name,
                c.data_type,
                c.is_nullable = 'YES' as is_nullable,
                c.column_default,
                c.character_maximum_length,
                c.numeric_precision,
                c.numeric_scale
            FROM information_schema.tables t
            JOIN information_schema.columns c ON t.table_name = c.table_name
            WHERE t.table_schema = 'public' 
                AND t.table_type = 'BASE TABLE'
            ORDER BY t.table_name, c.ordinal_position
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;

        // Group columns by table and build Table objects
        let mut tables = Vec::new();
        let mut current_table: Option<Table> = None;
        let mut current_columns = Vec::new();

        for row in rows {
            let table_name: String = row.get("table_name");
            let column_name: String = row.get("column_name");
            let data_type: String = row.get("data_type");
            let is_nullable: bool = row.get("is_nullable");
            let column_default: Option<String> = row.get("column_default");
            let max_length: Option<i32> = row.get("character_maximum_length");
            let precision: Option<i32> = row.get("numeric_precision");
            let scale: Option<i32> = row.get("numeric_scale");

            if let Some(ref table) = current_table {
                if table.name != table_name {
                    // Finish current table
                    let mut table = table.clone();
                    for column in current_columns.drain(..) {
                        table = table.add_column(column);
                    }
                    tables.push(table);

                    // Start new table
                    current_table = Some(Table::new(&table_name));
                }
            } else {
                current_table = Some(Table::new(&table_name));
            }

            // Create column from introspected data
            let column_type = self.map_pg_type_to_ignis_type(
                &data_type,
                is_nullable,
                max_length,
                precision,
                scale,
            );

            let mut column = crate::schema::Column::new(&column_name, column_type);
            if !is_nullable {
                column = column.not_null();
            }
            if let Some(default) = column_default {
                column = column.default(default);
            }

            current_columns.push(column);
        }

        // Don't forget the last table
        if let Some(table) = current_table {
            let mut table = table;
            for column in current_columns.drain(..) {
                table = table.add_column(column);
            }
            tables.push(table);
        }

        // Now get primary keys for all tables
        let primary_keys = self.get_primary_keys().await?;

        // Apply primary keys to tables
        for table in &mut tables {
            if let Some(pk) = primary_keys.get(&table.name) {
                *table = table.clone().set_primary_key(pk);
            }
        }

        Ok(tables)
    }

    /// Get primary keys for all tables
    async fn get_primary_keys(&self) -> Result<HashMap<String, String>> {
        let query = r#"
            SELECT 
                tc.table_name,
                string_agg(kcu.column_name, ', ' ORDER BY kcu.ordinal_position) as primary_key_columns
            FROM information_schema.table_constraints tc
            JOIN information_schema.key_column_usage kcu 
                ON tc.constraint_name = kcu.constraint_name
                AND tc.table_schema = kcu.table_schema
            WHERE tc.constraint_type = 'PRIMARY KEY'
                AND tc.table_schema = 'public'
            GROUP BY tc.table_name
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;
        let mut primary_keys = HashMap::new();

        for row in rows {
            let table_name: String = row.get("table_name");
            let pk_columns: String = row.get("primary_key_columns");
            primary_keys.insert(table_name, pk_columns);
        }

        Ok(primary_keys)
    }

    /// Introspect all tables from information_schema (original version for reference)
    pub async fn introspect_tables_old(&self) -> Result<Vec<Table>> {
        let query = r#"
            SELECT 
                t.table_name,
                c.column_name,
                c.data_type,
                c.is_nullable = 'YES' as is_nullable,
                c.column_default,
                c.character_maximum_length,
                c.numeric_precision,
                c.numeric_scale
            FROM information_schema.tables t
            JOIN information_schema.columns c ON t.table_name = c.table_name
            WHERE t.table_schema = 'public' 
                AND t.table_type = 'BASE TABLE'
            ORDER BY t.table_name, c.ordinal_position
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;

        // Group columns by table and build Table objects
        let mut tables = Vec::new();
        let mut current_table: Option<Table> = None;
        let mut current_columns = Vec::new();

        for row in rows {
            let table_name: String = row.get("table_name");
            let column_name: String = row.get("column_name");
            let data_type: String = row.get("data_type");
            let is_nullable: bool = row.get("is_nullable");
            let column_default: Option<String> = row.get("column_default");
            let max_length: Option<i32> = row.get("character_maximum_length");
            let precision: Option<i32> = row.get("numeric_precision");
            let scale: Option<i32> = row.get("numeric_scale");

            if let Some(ref table) = current_table {
                if table.name != table_name {
                    // Finish current table
                    let mut table = table.clone();
                    for column in current_columns.drain(..) {
                        table = table.add_column(column);
                    }
                    tables.push(table);

                    // Start new table
                    current_table = Some(Table::new(&table_name));
                }
            } else {
                current_table = Some(Table::new(&table_name));
            }

            // Create column from introspected data
            let column_type = self.map_pg_type_to_ignis_type(
                &data_type,
                is_nullable,
                max_length,
                precision,
                scale,
            );

            let mut column = crate::schema::Column::new(&column_name, column_type);
            if !is_nullable {
                column = column.not_null();
            }
            if let Some(default) = column_default {
                column = column.default(default);
            }

            current_columns.push(column);
        }

        // Don't forget the last table
        if let Some(table) = current_table {
            let mut table = table;
            for column in current_columns {
                table = table.add_column(column);
            }
            tables.push(table);
        }

        Ok(tables)
    }

    /// Introspect all views including materialized views
    pub async fn introspect_views(&self) -> Result<Vec<View>> {
        let mut views = Vec::new();

        // Introspect regular views
        let regular_views_query = r#"
            SELECT 
                viewname as name,
                definition
            FROM pg_views
            WHERE schemaname = 'public'
            ORDER BY viewname
        "#;

        let regular_rows = sqlx::query(regular_views_query)
            .fetch_all(&self.pool)
            .await?;
        for row in regular_rows {
            let name: String = row.get("name");
            let definition: String = row.get("definition");

            let mut view = crate::schema::View::new(&name);
            view.set_ddl(&definition);
            view.set_materialized(false);
            views.push(view);
        }

        // Introspect materialized views
        let materialized_views_query = r#"
            SELECT 
                matviewname as name,
                definition
            FROM pg_matviews
            WHERE schemaname = 'public'
            ORDER BY matviewname
        "#;

        let materialized_rows = sqlx::query(materialized_views_query)
            .fetch_all(&self.pool)
            .await?;
        for row in materialized_rows {
            let name: String = row.get("name");
            let definition: String = row.get("definition");

            let mut view = crate::schema::View::new(&name);
            view.set_ddl(&definition);
            view.set_materialized(true);
            views.push(view);
        }

        Ok(views)
    }

    /// Introspect indexes, constraints, and foreign keys
    pub async fn introspect_indexes(&self) -> Result<Vec<Index>> {
        let query = r#"
            SELECT 
                indexname as name,
                tablename as table_name,
                indexdef as definition
            FROM pg_indexes
            WHERE schemaname = 'public'
            ORDER BY indexname
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;
        let mut indexes = Vec::new();

        for row in rows {
            let name: String = row.get("name");
            let table_name: String = row.get("table_name");
            let definition: String = row.get("definition");

            // Parse the index definition to extract properties
            let is_unique = definition.contains("UNIQUE");
            let columns = vec![table_name]; // For now, just use table name as placeholder

            let index = crate::schema::Index::new(&name, columns, is_unique);

            indexes.push(index);
        }

        Ok(indexes)
    }

    /// Introspect composite types (our new feature!)
    pub async fn introspect_composite_types(&self) -> Result<Vec<CompositeType>> {
        let query = r#"
            SELECT 
                t.typname as name,
                a.attname as field_name,
                pg_catalog.format_type(a.atttypid, a.atttypmod) as field_type,
                a.attnotnull as is_not_null
            FROM pg_type t
            JOIN pg_class c ON c.oid = t.typrelid
            JOIN pg_attribute a ON a.attrelid = c.oid
            WHERE t.typtype = 'c' 
                AND c.relkind = 'c'
                AND a.attnum > 0
                AND a.attisdropped = false
            ORDER BY t.typname, a.attnum
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;
        let mut composite_types = Vec::new();
        let mut current_type: Option<CompositeType> = None;
        let mut current_fields: Vec<CompositeField> = Vec::new();

        for row in rows {
            let type_name: String = row.get("name");
            let field_name: String = row.get("field_name");
            let field_type: String = row.get("field_type");
            let is_not_null: bool = row.get("is_not_null");

            if let Some(ref composite_type) = current_type {
                if composite_type.name != type_name {
                    // Finish current type
                    let mut composite_type = composite_type.clone();
                    for field in current_fields.drain(..) {
                        composite_type =
                            composite_type.with_field(field.name, field.field_type, field.nullable);
                    }
                    composite_types.push(composite_type);

                    // Start new type
                    current_type = Some(CompositeType::new(&type_name));
                }
            } else {
                current_type = Some(CompositeType::new(&type_name));
            }

            // Create field from introspected data
            let field = crate::schema::CompositeField {
                name: field_name,
                field_type,
                nullable: !is_not_null,
            };

            current_fields.push(field);
        }

        // Don't forget the last type
        if let Some(composite_type) = current_type {
            let mut composite_type = composite_type;
            for field in current_fields {
                composite_type =
                    composite_type.with_field(field.name, field.field_type, field.nullable);
            }
            composite_types.push(composite_type);
        }

        Ok(composite_types)
    }

    /// Introspect stored functions
    pub async fn introspect_functions(&self) -> Result<Vec<StoredFunction>> {
        let query = r#"
            SELECT 
                p.proname as name,
                n.nspname as schema_name,
                pg_get_function_arguments(p.oid) as parameters,
                pg_get_function_result(p.oid) as return_type,
                l.lanname as language,
                p.prosrc as body,
                CASE p.provolatile 
                    WHEN 'i' THEN 'IMMUTABLE'
                    WHEN 's' THEN 'STABLE'
                    WHEN 'v' THEN 'VOLATILE'
                END as volatility,
                CASE p.prosecdef
                    WHEN true THEN 'DEFINER'
                    WHEN false THEN 'INVOKER'
                END as security,
                p.proisstrict as is_strict
            FROM pg_proc p
            JOIN pg_namespace n ON p.pronamespace = n.oid
            JOIN pg_language l ON p.prolang = l.oid
            WHERE n.nspname = 'public' 
                AND p.prokind = 'f'
            ORDER BY p.proname
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;
        let mut functions = Vec::new();

        for row in rows {
            let name: String = row.get("name");
            let schema_name: Option<String> = row.get("schema_name");
            let parameters_str: String = row.get("parameters");
            let return_type: Option<String> = row.get("return_type");
            let language: String = row.get("language");
            let body: String = row.get("body");
            let volatility: String = row.get("volatility");
            let security: String = row.get("security");
            let is_strict: bool = row.get("is_strict");

            let function = StoredFunction {
                name,
                schema: schema_name,
                parameters: self.parse_function_parameters(&parameters_str),
                return_type,
                language: self.map_language(&language),
                body,
                volatility: self.map_volatility(&volatility),
                security: self.map_security(&security),
                strict: is_strict,
            };

            functions.push(function);
        }

        Ok(functions)
    }

    /// Introspect stored procedures  
    pub async fn introspect_procedures(&self) -> Result<Vec<StoredProcedure>> {
        let query = r#"
            SELECT 
                p.proname as name,
                n.nspname as schema_name,
                pg_get_function_arguments(p.oid) as parameters,
                l.lanname as language,
                p.prosrc as body,
                CASE p.prosecdef
                    WHEN true THEN 'DEFINER'
                    WHEN false THEN 'INVOKER'
                END as security
            FROM pg_proc p
            JOIN pg_namespace n ON p.pronamespace = n.oid
            JOIN pg_language l ON p.prolang = l.oid
            WHERE n.nspname = 'public' 
                AND p.prokind = 'p'
            ORDER BY p.proname
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;
        let mut procedures = Vec::new();

        for row in rows {
            let name: String = row.get("name");
            let schema_name: Option<String> = row.get("schema_name");
            let parameters_str: String = row.get("parameters");
            let language: String = row.get("language");
            let body: String = row.get("body");
            let security: String = row.get("security");

            let procedure = StoredProcedure {
                name,
                schema: schema_name,
                parameters: self.parse_function_parameters(&parameters_str),
                language: self.map_language(&language),
                body,
                security: self.map_security(&security),
            };

            procedures.push(procedure);
        }

        Ok(procedures)
    }

    /// Introspect triggers
    pub async fn introspect_triggers(&self) -> Result<Vec<Trigger>> {
        let query = r#"
            SELECT 
                t.tgname as name,
                n.nspname as schema_name,
                c.relname as table_name,
                tn.nspname as table_schema,
                CASE t.tgtype::int & 66 
                    WHEN 2 THEN 'BEFORE'
                    WHEN 64 THEN 'AFTER'
                    ELSE 'INSTEAD OF'
                END as timing,
                CASE 
                    WHEN t.tgtype::int & 4 != 0 THEN 'INSERT'
                    WHEN t.tgtype::int & 8 != 0 THEN 'DELETE'  
                    WHEN t.tgtype::int & 16 != 0 THEN 'UPDATE'
                    ELSE 'OTHER'
                END as event,
                CASE t.tgtype::int & 1
                    WHEN 0 THEN 'STATEMENT'
                    WHEN 1 THEN 'ROW'
                END as orientation,
                p.proname as function_name,
                fn.nspname as function_schema,
                pg_get_triggerdef(t.oid) as condition
            FROM pg_trigger t
            JOIN pg_class c ON t.tgrelid = c.oid
            JOIN pg_namespace n ON c.relnamespace = n.oid
            LEFT JOIN pg_namespace tn ON c.relnamespace = tn.oid
            JOIN pg_proc p ON t.tgfoid = p.oid
            LEFT JOIN pg_namespace fn ON p.pronamespace = fn.oid
            WHERE n.nspname = 'public'
                AND NOT t.tgisinternal
            ORDER BY t.tgname
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;
        let mut triggers = Vec::new();

        for row in rows {
            let name: String = row.get("name");
            let schema_name: Option<String> = row.get("schema_name");
            let table_name: String = row.get("table_name");
            let table_schema: Option<String> = row.get("table_schema");
            let timing: String = row.get("timing");
            let event: String = row.get("event");
            let orientation: String = row.get("orientation");
            let function_name: String = row.get("function_name");
            let function_schema: Option<String> = row.get("function_schema");
            let condition: Option<String> = row.get("condition");

            let trigger = Trigger {
                name,
                schema: schema_name,
                table_name,
                table_schema,
                timing: self.map_trigger_timing(&timing),
                events: vec![self.map_trigger_event(&event)],
                orientation: self.map_trigger_orientation(&orientation),
                function_name,
                function_schema,
                condition,
                update_columns: None, // TODO: Parse from condition if needed
                referencing: None,    // TODO: Parse referencing clause if needed
            };

            triggers.push(trigger);
        }

        Ok(triggers)
    }

    /// Introspect roles and grants
    pub async fn introspect_permissions(&self) -> Result<(Vec<Role>, Vec<Grant>)> {
        // Introspect roles
        let roles_query = r#"
            SELECT 
                rolname as name,
                rolcanlogin as can_login,
                rolsuper as is_superuser,
                rolcreatedb as can_create_db,
                rolcreaterole as can_create_role
            FROM pg_roles
            WHERE rolname NOT IN ('postgres', 'pg_signal_backend')
            ORDER BY rolname
        "#;

        let role_rows = sqlx::query(roles_query).fetch_all(&self.pool).await?;
        let mut roles = Vec::new();

        for row in role_rows {
            let name: String = row.get("name");
            let can_login: bool = row.get("can_login");
            let is_superuser: bool = row.get("is_superuser");
            let can_create_db: bool = row.get("can_create_db");
            let can_create_role: bool = row.get("can_create_role");

            let role = crate::schema::Role::new(&name)
                .with_login(can_login)
                .with_superuser(is_superuser)
                .with_createdb(can_create_db)
                .with_createrole(can_create_role);

            roles.push(role);
        }

        // Introspect grants
        let grants_query = r#"
            SELECT 
                grantee,
                table_name,
                privilege_type,
                is_grantable
            FROM information_schema.role_table_grants
            WHERE table_schema = 'public'
            ORDER BY grantee, table_name, privilege_type
        "#;

        let grant_rows = sqlx::query(grants_query).fetch_all(&self.pool).await?;
        let mut grants = Vec::new();

        for row in grant_rows {
            let grantee: String = row.get("grantee");
            let table_name: String = row.get("table_name");
            let privilege: String = row.get("privilege_type");
            let is_grantable: String = row.get("is_grantable");

            let privilege_enum = match privilege.as_str() {
                "SELECT" => crate::schema::Privilege::Select,
                "INSERT" => crate::schema::Privilege::Insert,
                "UPDATE" => crate::schema::Privilege::Update,
                "DELETE" => crate::schema::Privilege::Delete,
                "ALL" => crate::schema::Privilege::All,
                _ => crate::schema::Privilege::Select, // Default fallback
            };

            let grant = crate::schema::Grant::new(
                privilege_enum,
                crate::schema::GrantTarget::Table {
                    table: table_name,
                    schema: None,
                },
                &grantee,
            )
            .with_grant_option(is_grantable == "YES");

            grants.push(grant);
        }

        Ok((roles, grants))
    }

    /// Parse function parameters from PostgreSQL format
    fn parse_function_parameters(
        &self,
        params_str: &str,
    ) -> Vec<crate::schema::ProcedureParameter> {
        // Simple parsing for now - this could be enhanced for complex cases
        if params_str.is_empty() {
            return Vec::new();
        }

        // Split by commas and parse each parameter
        params_str
            .split(',')
            .map(|param| {
                let param = param.trim();
                let parts: Vec<&str> = param.split_whitespace().collect();

                if parts.len() >= 2 {
                    crate::schema::ProcedureParameter {
                        name: parts[0].to_string(),
                        data_type: parts[1].to_string(),
                        mode: crate::schema::ParameterMode::In, // Default to IN
                        default_value: None,
                    }
                } else {
                    // Fallback for malformed parameters
                    crate::schema::ProcedureParameter {
                        name: "param".to_string(),
                        data_type: param.to_string(),
                        mode: crate::schema::ParameterMode::In,
                        default_value: None,
                    }
                }
            })
            .collect()
    }

    /// Map PostgreSQL language name to Ignis language enum
    fn map_language(&self, lang: &str) -> crate::schema::ProcedureLanguage {
        match lang.to_lowercase().as_str() {
            "sql" => crate::schema::ProcedureLanguage::Sql,
            "plpgsql" => crate::schema::ProcedureLanguage::PlPgSql,
            "c" => crate::schema::ProcedureLanguage::C,
            "python" | "plpython3u" | "plpythonu" => crate::schema::ProcedureLanguage::PlPython3,
            "javascript" | "plv8" => {
                crate::schema::ProcedureLanguage::Custom("javascript".to_string())
            }
            _ => crate::schema::ProcedureLanguage::Sql, // Default fallback
        }
    }

    /// Map PostgreSQL volatility to Ignis volatility enum
    fn map_volatility(&self, volatility: &str) -> crate::schema::FunctionVolatility {
        match volatility.to_uppercase().as_str() {
            "IMMUTABLE" => crate::schema::FunctionVolatility::Immutable,
            "STABLE" => crate::schema::FunctionVolatility::Stable,
            "VOLATILE" => crate::schema::FunctionVolatility::Volatile,
            _ => crate::schema::FunctionVolatility::Volatile, // Default fallback
        }
    }

    /// Map PostgreSQL security to Ignis security enum
    fn map_security(&self, security: &str) -> crate::schema::FunctionSecurity {
        match security.to_uppercase().as_str() {
            "DEFINER" => crate::schema::FunctionSecurity::Definer,
            "INVOKER" => crate::schema::FunctionSecurity::Invoker,
            _ => crate::schema::FunctionSecurity::Invoker, // Default fallback
        }
    }

    /// Map PostgreSQL trigger timing to Ignis timing enum
    fn map_trigger_timing(&self, timing: &str) -> crate::schema::TriggerTiming {
        match timing.to_uppercase().as_str() {
            "BEFORE" => crate::schema::TriggerTiming::Before,
            "AFTER" => crate::schema::TriggerTiming::After,
            "INSTEAD OF" => crate::schema::TriggerTiming::InsteadOf,
            _ => crate::schema::TriggerTiming::Before, // Default fallback
        }
    }

    /// Map PostgreSQL trigger event to Ignis event enum
    fn map_trigger_event(&self, event: &str) -> crate::schema::TriggerEvent {
        match event.to_uppercase().as_str() {
            "INSERT" => crate::schema::TriggerEvent::Insert,
            "UPDATE" => crate::schema::TriggerEvent::Update,
            "DELETE" => crate::schema::TriggerEvent::Delete,
            "TRUNCATE" => crate::schema::TriggerEvent::Truncate,
            _ => crate::schema::TriggerEvent::Insert, // Default fallback
        }
    }

    /// Map PostgreSQL trigger orientation to Ignis orientation enum
    fn map_trigger_orientation(&self, orientation: &str) -> crate::schema::TriggerOrientation {
        match orientation.to_uppercase().as_str() {
            "ROW" => crate::schema::TriggerOrientation::Row,
            "STATEMENT" => crate::schema::TriggerOrientation::Statement,
            _ => crate::schema::TriggerOrientation::Row, // Default fallback
        }
    }

    /// Map PostgreSQL data type to Ignis-DB ColumnType
    fn map_pg_type_to_ignis_type(
        &self,
        pg_type: &str,
        _is_nullable: bool,
        max_length: Option<i32>,
        precision: Option<i32>,
        scale: Option<i32>,
    ) -> crate::schema::ColumnType {
        match pg_type.to_lowercase().as_str() {
            "integer" | "int" | "int4" => crate::schema::ColumnType::Int4,
            "bigint" | "int8" => crate::schema::ColumnType::Int8,
            "smallint" | "int2" => crate::schema::ColumnType::Int2,
            "text" => crate::schema::ColumnType::Text,
            "varchar" | "character varying" => {
                if let Some(length) = max_length {
                    crate::schema::ColumnType::Varchar(Some(length as usize))
                } else {
                    crate::schema::ColumnType::Varchar(None)
                }
            }
            "char" | "character" => crate::schema::ColumnType::Char,
            "boolean" | "bool" => crate::schema::ColumnType::Bool,
            "timestamp with time zone" | "timestamptz" => crate::schema::ColumnType::Timestamptz,
            "timestamp without time zone" | "timestamp" => crate::schema::ColumnType::Timestamptz,
            "date" => crate::schema::ColumnType::Date,
            "time" => crate::schema::ColumnType::Time,
            "uuid" => crate::schema::ColumnType::Uuid,
            "numeric" | "decimal" => match (precision, scale) {
                (Some(p), Some(s)) => {
                    crate::schema::ColumnType::Numeric(Some(p as usize), Some(s as usize))
                }
                (Some(p), None) => crate::schema::ColumnType::Numeric(Some(p as usize), None),
                (None, Some(s)) => crate::schema::ColumnType::Numeric(None, Some(s as usize)),
                (None, None) => crate::schema::ColumnType::Numeric(None, None),
            },
            "jsonb" => crate::schema::ColumnType::Jsonb,
            "json" => crate::schema::ColumnType::Json,
            "bytea" => crate::schema::ColumnType::Text, // Use Text for bytea for now
            "real" | "float4" => crate::schema::ColumnType::Numeric(None, None), // Use Numeric for float
            "double precision" | "float8" => crate::schema::ColumnType::Numeric(None, None), // Use Numeric for double
            // Handle arrays: integer[] -> Array(Box<ColumnType::Int4>)
            array_type if array_type.ends_with("[]") => {
                let base_type = &array_type[..array_type.len() - 2];
                let base_column_type =
                    self.map_pg_type_to_ignis_type(base_type, false, None, None, None);
                crate::schema::ColumnType::Array(Box::new(base_column_type))
            }
            // Handle composite types and other custom types
            custom => crate::schema::ColumnType::Custom(custom.to_string()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pg_type_mapping() {
        // Test the type mapping function directly without creating a DatabaseIntrospector
        // This avoids the Tokio context requirement

        // Test basic type mapping
        let int_type = map_pg_type_to_ignis_type_direct("integer", false, None, None, None);
        assert!(matches!(int_type, crate::schema::ColumnType::Int4));

        let varchar_type =
            map_pg_type_to_ignis_type_direct("varchar", false, Some(255), None, None);
        assert!(matches!(
            varchar_type,
            crate::schema::ColumnType::Varchar(Some(255))
        ));

        let array_type = map_pg_type_to_ignis_type_direct("integer[]", false, None, None, None);
        assert!(matches!(array_type, crate::schema::ColumnType::Array(_)));
    }

    // Helper function for testing type mapping without Tokio context
    fn map_pg_type_to_ignis_type_direct(
        pg_type: &str,
        is_nullable: bool,
        max_length: Option<i32>,
        precision: Option<i32>,
        scale: Option<i32>,
    ) -> crate::schema::ColumnType {
        match pg_type.to_lowercase().as_str() {
            "integer" | "int" | "int4" => crate::schema::ColumnType::Int4,
            "bigint" | "int8" => crate::schema::ColumnType::Int8,
            "smallint" | "int2" => crate::schema::ColumnType::Int2,
            "text" => crate::schema::ColumnType::Text,
            "varchar" | "character varying" => {
                if let Some(length) = max_length {
                    crate::schema::ColumnType::Varchar(Some(length as usize))
                } else {
                    crate::schema::ColumnType::Varchar(None)
                }
            }
            "char" | "character" => crate::schema::ColumnType::Char,
            "boolean" | "bool" => crate::schema::ColumnType::Bool,
            "timestamp with time zone" | "timestamptz" => crate::schema::ColumnType::Timestamptz,
            "timestamp without time zone" | "timestamp" => crate::schema::ColumnType::Timestamptz,
            "date" => crate::schema::ColumnType::Date,
            "time" => crate::schema::ColumnType::Time,
            "uuid" => crate::schema::ColumnType::Uuid,
            "numeric" | "decimal" => match (precision, scale) {
                (Some(p), Some(s)) => {
                    crate::schema::ColumnType::Numeric(Some(p as usize), Some(s as usize))
                }
                (Some(p), None) => crate::schema::ColumnType::Numeric(Some(p as usize), None),
                (None, Some(s)) => crate::schema::ColumnType::Numeric(None, Some(s as usize)),
                (None, None) => crate::schema::ColumnType::Numeric(None, None),
            },
            "jsonb" => crate::schema::ColumnType::Jsonb,
            "json" => crate::schema::ColumnType::Json,
            "bytea" => crate::schema::ColumnType::Text, // Use Text for bytea for now
            "real" | "float4" => crate::schema::ColumnType::Numeric(None, None), // Use Numeric for float
            "double precision" | "float8" => crate::schema::ColumnType::Numeric(None, None), // Use Numeric for double
            // Handle arrays: integer[] -> Array(Box<ColumnType::Int4>)
            array_type if array_type.ends_with("[]") => {
                let base_type = &array_type[..array_type.len() - 2];
                let base_column_type =
                    map_pg_type_to_ignis_type_direct(base_type, false, None, None, None);
                crate::schema::ColumnType::Array(Box::new(base_column_type))
            }
            // Handle composite types and other custom types
            custom => crate::schema::ColumnType::Custom(custom.to_string()),
        }
    }
}