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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
//! Baseline Migration System for Brownfield Database Adoption
//!
//! This module provides the revolutionary capability to adopt existing PostgreSQL databases
//! by creating a baseline migration that represents the current state of the database.
//! This is the key differentiator that allows Ignis-DB to work with brownfield projects.

use crate::migrate::strategy::{SchemaChange, SchemaChangeType};
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use sqlx::{PgPool, Row};

/// Represents a baseline migration for an existing database
/// This captures the complete state of a database at a point in time
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BaselineMigration {
    /// Unique identifier for this baseline
    pub id: String,

    /// SHA256 checksum of the complete schema
    pub schema_checksum: String,

    /// The complete SQL to recreate the database schema
    pub baseline_sql: String,

    /// When this baseline was created
    pub created_at: DateTime<Utc>,

    /// Database version info
    pub database_version: String,

    /// Schema statistics
    pub statistics: SchemaStatistics,
}

/// Statistics about the baseline schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaStatistics {
    pub table_count: usize,
    pub view_count: usize,
    pub index_count: usize,
    pub function_count: usize,
    pub trigger_count: usize,
    pub composite_type_count: usize,
    pub total_columns: usize,
    pub total_constraints: usize,
}

/// Manager for baseline migration operations
pub struct BaselineMigrationManager {
    pool: PgPool,
}

impl BaselineMigrationManager {
    /// Create a new baseline migration manager
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    /// Create a baseline migration from the current database state
    pub async fn create_baseline(&self, name: Option<String>) -> Result<BaselineMigration> {
        println!("📸 Creating baseline snapshot of current database...");

        // Get complete schema DDL
        let schema_ddl = self.extract_complete_schema_ddl().await?;

        // Calculate checksum
        let checksum = Self::calculate_schema_checksum(&schema_ddl);

        // Get statistics
        let statistics = self.calculate_schema_statistics().await?;

        // Get database version
        let database_version = self.get_database_version().await?;

        // Generate unique ID
        let id = if let Some(name) = name {
            format!(
                "{}_baseline_{}",
                chrono::Utc::now().format("%Y%m%d_%H%M%S"),
                name.to_lowercase().replace(' ', "_")
            )
        } else {
            format!("{}_baseline", chrono::Utc::now().format("%Y%m%d_%H%M%S"))
        };

        let baseline = BaselineMigration {
            id: id.clone(),
            schema_checksum: checksum,
            baseline_sql: schema_ddl,
            created_at: chrono::Utc::now(),
            database_version,
            statistics,
        };

        println!("✅ Baseline created: {}", id);
        println!(
            "   📊 Tables: {}, Views: {}, Indexes: {}",
            baseline.statistics.table_count,
            baseline.statistics.view_count,
            baseline.statistics.index_count
        );
        println!("   🔒 Checksum: {}...", &baseline.schema_checksum[..16]);

        Ok(baseline)
    }

    /// Extract complete schema DDL from the database
    async fn extract_complete_schema_ddl(&self) -> Result<String> {
        let mut ddl = String::new();

        // Header
        ddl.push_str("-- Ignis-DB Baseline Migration\n");
        ddl.push_str(&format!(
            "-- Generated at: {}\n",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
        ));
        ddl.push_str("-- This represents the complete schema state at baseline creation\n\n");

        // 1. Extract custom types
        ddl.push_str(
            "-- ============================================================================\n",
        );
        ddl.push_str("-- CUSTOM TYPES\n");
        ddl.push_str(
            "-- ============================================================================\n\n",
        );
        let types_sql = self.extract_custom_types().await?;
        ddl.push_str(&types_sql);
        ddl.push_str("\n");

        // 2. Extract functions (needed before tables that might use them)
        ddl.push_str(
            "-- ============================================================================\n",
        );
        ddl.push_str("-- FUNCTIONS\n");
        ddl.push_str(
            "-- ============================================================================\n\n",
        );
        let functions_sql = self.extract_functions().await?;
        ddl.push_str(&functions_sql);
        ddl.push_str("\n");

        // 3. Extract tables
        ddl.push_str(
            "-- ============================================================================\n",
        );
        ddl.push_str("-- TABLES\n");
        ddl.push_str(
            "-- ============================================================================\n\n",
        );
        let tables_sql = self.extract_tables().await?;
        ddl.push_str(&tables_sql);
        ddl.push_str("\n");

        // 4. Extract views
        ddl.push_str(
            "-- ============================================================================\n",
        );
        ddl.push_str("-- VIEWS\n");
        ddl.push_str(
            "-- ============================================================================\n\n",
        );
        let views_sql = self.extract_views().await?;
        ddl.push_str(&views_sql);
        ddl.push_str("\n");

        // 5. Extract indexes
        ddl.push_str(
            "-- ============================================================================\n",
        );
        ddl.push_str("-- INDEXES\n");
        ddl.push_str(
            "-- ============================================================================\n\n",
        );
        let indexes_sql = self.extract_indexes().await?;
        ddl.push_str(&indexes_sql);
        ddl.push_str("\n");

        // 6. Extract triggers
        ddl.push_str(
            "-- ============================================================================\n",
        );
        ddl.push_str("-- TRIGGERS\n");
        ddl.push_str(
            "-- ============================================================================\n\n",
        );
        let triggers_sql = self.extract_triggers().await?;
        ddl.push_str(&triggers_sql);
        ddl.push_str("\n");

        // 7. Extract constraints (foreign keys, checks, etc.)
        ddl.push_str(
            "-- ============================================================================\n",
        );
        ddl.push_str("-- CONSTRAINTS\n");
        ddl.push_str(
            "-- ============================================================================\n\n",
        );
        let constraints_sql = self.extract_constraints().await?;
        ddl.push_str(&constraints_sql);

        Ok(ddl)
    }

    /// Extract custom type definitions
    async fn extract_custom_types(&self) -> Result<String> {
        let query = r#"
            SELECT 
                t.typname AS type_name,
                n.nspname AS schema_name,
                CASE t.typtype
                    WHEN 'c' THEN 'COMPOSITE'
                    WHEN 'e' THEN 'ENUM'
                    WHEN 'd' THEN 'DOMAIN'
                    ELSE 'OTHER'
                END AS type_kind,
                pg_catalog.format_type(t.oid, NULL) AS formatted_type,
                obj_description(t.oid, 'pg_type') AS description
            FROM pg_catalog.pg_type t
            JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
            WHERE n.nspname = 'public'
                AND t.typtype IN ('c', 'e', 'd')
                AND NOT EXISTS (
                    SELECT 1 FROM pg_catalog.pg_class c 
                    WHERE c.oid = t.typrelid AND c.relkind IN ('r', 'v')
                )
            ORDER BY t.typname
        "#;

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

        for row in rows {
            let type_name: String = row.get("type_name");
            let type_kind: String = row.get("type_kind");

            match type_kind.as_str() {
                "COMPOSITE" => {
                    let composite_sql = self.get_composite_type_definition(&type_name).await?;
                    sql.push_str(&composite_sql);
                    sql.push_str("\n");
                }
                "ENUM" => {
                    let enum_sql = self.get_enum_type_definition(&type_name).await?;
                    sql.push_str(&enum_sql);
                    sql.push_str("\n");
                }
                _ => {}
            }
        }

        Ok(sql)
    }

    /// Get composite type definition
    async fn get_composite_type_definition(&self, type_name: &str) -> Result<String> {
        let query = r#"
            SELECT 
                a.attname AS field_name,
                pg_catalog.format_type(a.atttypid, a.atttypmod) AS field_type
            FROM pg_catalog.pg_type t
            JOIN pg_catalog.pg_class c ON c.oid = t.typrelid
            JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
            WHERE t.typname = $1
                AND a.attnum > 0
                AND NOT a.attisdropped
            ORDER BY a.attnum
        "#;

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

        let mut sql = format!("CREATE TYPE \"{}\" AS (\n", type_name);
        let fields: Vec<String> = rows
            .iter()
            .map(|row| {
                let field_name: String = row.get("field_name");
                let field_type: String = row.get("field_type");
                format!("    \"{}\" {}", field_name, field_type)
            })
            .collect();

        sql.push_str(&fields.join(",\n"));
        sql.push_str("\n);\n");

        Ok(sql)
    }

    /// Get enum type definition
    async fn get_enum_type_definition(&self, type_name: &str) -> Result<String> {
        let query = r#"
            SELECT enumlabel
            FROM pg_catalog.pg_enum e
            JOIN pg_catalog.pg_type t ON t.oid = e.enumtypid
            WHERE t.typname = $1
            ORDER BY e.enumsortorder
        "#;

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

        let mut sql = format!("CREATE TYPE \"{}\" AS ENUM (\n", type_name);
        let values: Vec<String> = rows
            .iter()
            .map(|row| {
                let label: String = row.get("enumlabel");
                format!("    '{}'", label)
            })
            .collect();

        sql.push_str(&values.join(",\n"));
        sql.push_str("\n);\n");

        Ok(sql)
    }

    /// Extract table definitions
    async fn extract_tables(&self) -> Result<String> {
        // Use pg_dump style extraction for accuracy

        // Since pg_get_tabledef doesn't exist, we'll build it manually
        let tables_query = r#"
            SELECT tablename 
            FROM pg_tables 
            WHERE schemaname = 'public'
            ORDER BY tablename
        "#;

        let tables = sqlx::query(tables_query).fetch_all(&self.pool).await?;
        let mut sql = String::new();

        for table in tables {
            let table_name: String = table.get("tablename");
            let table_def = self.get_table_definition(&table_name).await?;
            sql.push_str(&format!("-- Table: {}\n", table_name));
            sql.push_str(&table_def);
            sql.push_str("\n");
        }

        Ok(sql)
    }

    /// Get complete table definition
    async fn get_table_definition(&self, table_name: &str) -> Result<String> {
        let columns_query = r#"
            SELECT 
                column_name,
                data_type,
                character_maximum_length,
                numeric_precision,
                numeric_scale,
                is_nullable,
                column_default
            FROM information_schema.columns
            WHERE table_schema = 'public' AND table_name = $1
            ORDER BY ordinal_position
        "#;

        let columns = sqlx::query(columns_query)
            .bind(table_name)
            .fetch_all(&self.pool)
            .await?;

        let mut sql = format!("CREATE TABLE \"{}\" (\n", table_name);
        let mut column_defs = Vec::new();

        for col in columns {
            let col_name: String = col.get("column_name");
            let _data_type: String = col.get("data_type");
            let is_nullable: String = col.get("is_nullable");
            let column_default: Option<String> = col.get("column_default");

            let mut def = format!("    \"{}\" {}", col_name, self.format_column_type(&col));

            if is_nullable == "NO" {
                def.push_str(" NOT NULL");
            }

            if let Some(default) = column_default {
                def.push_str(&format!(" DEFAULT {}", default));
            }

            column_defs.push(def);
        }

        // Add primary key constraint
        let pk_query = r#"
            SELECT constraint_name, column_name
            FROM information_schema.key_column_usage
            WHERE table_schema = 'public' 
                AND table_name = $1
                AND constraint_name IN (
                    SELECT constraint_name 
                    FROM information_schema.table_constraints
                    WHERE table_schema = 'public' 
                        AND table_name = $1 
                        AND constraint_type = 'PRIMARY KEY'
                )
            ORDER BY ordinal_position
        "#;

        let pk_rows = sqlx::query(pk_query)
            .bind(table_name)
            .fetch_all(&self.pool)
            .await?;

        if !pk_rows.is_empty() {
            let pk_columns: Vec<String> = pk_rows
                .iter()
                .map(|row| row.get::<String, _>("column_name"))
                .collect();
            column_defs.push(format!(
                "    PRIMARY KEY (\"{}\")",
                pk_columns.join("\", \"")
            ));
        }

        sql.push_str(&column_defs.join(",\n"));
        sql.push_str("\n);\n");

        Ok(sql)
    }

    /// Format column type from information_schema
    fn format_column_type(&self, col: &sqlx::postgres::PgRow) -> String {
        let data_type: String = col.get("data_type");
        let max_length: Option<i32> = col.get("character_maximum_length");
        let precision: Option<i32> = col.get("numeric_precision");
        let scale: Option<i32> = col.get("numeric_scale");

        match data_type.as_str() {
            "character varying" => {
                if let Some(len) = max_length {
                    format!("VARCHAR({})", len)
                } else {
                    "VARCHAR".to_string()
                }
            }
            "character" => {
                if let Some(len) = max_length {
                    format!("CHAR({})", len)
                } else {
                    "CHAR".to_string()
                }
            }
            "numeric" => {
                if let (Some(p), Some(s)) = (precision, scale) {
                    format!("NUMERIC({}, {})", p, s)
                } else if let Some(p) = precision {
                    format!("NUMERIC({})", p)
                } else {
                    "NUMERIC".to_string()
                }
            }
            dt => dt.to_uppercase(),
        }
    }

    /// Extract view definitions
    async fn extract_views(&self) -> Result<String> {
        let query = r#"
            SELECT 
                viewname,
                definition
            FROM pg_views
            WHERE schemaname = 'public'
            ORDER BY viewname
        "#;

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

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

            sql.push_str(&format!("-- View: {}\n", view_name));
            sql.push_str(&format!("CREATE VIEW \"{}\" AS\n{}", view_name, definition));
            if !definition.ends_with(';') {
                sql.push_str(";");
            }
            sql.push_str("\n\n");
        }

        Ok(sql)
    }

    /// Extract function definitions
    async fn extract_functions(&self) -> Result<String> {
        let query = r#"
            SELECT 
                p.proname AS function_name,
                pg_catalog.pg_get_functiondef(p.oid) AS definition
            FROM pg_catalog.pg_proc p
            JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
            WHERE n.nspname = 'public'
            ORDER BY p.proname
        "#;

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

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

            sql.push_str(&format!("-- Function: {}\n", function_name));
            sql.push_str(&definition);
            if !definition.ends_with(';') {
                sql.push_str(";");
            }
            sql.push_str("\n\n");
        }

        Ok(sql)
    }

    /// Extract index definitions
    async fn extract_indexes(&self) -> Result<String> {
        let query = r#"
            SELECT 
                indexname,
                indexdef
            FROM pg_indexes
            WHERE schemaname = 'public'
                AND indexname NOT LIKE '%_pkey'
            ORDER BY tablename, indexname
        "#;

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

        for row in rows {
            let index_name: String = row.get("indexname");
            let index_def: String = row.get("indexdef");

            sql.push_str(&format!("-- Index: {}\n", index_name));
            sql.push_str(&index_def);
            if !index_def.ends_with(';') {
                sql.push_str(";");
            }
            sql.push_str("\n");
        }

        Ok(sql)
    }

    /// Extract trigger definitions
    async fn extract_triggers(&self) -> Result<String> {
        let query = r#"
            SELECT 
                t.tgname AS trigger_name,
                c.relname AS table_name,
                pg_catalog.pg_get_triggerdef(t.oid) AS definition
            FROM pg_catalog.pg_trigger t
            JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid
            JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE n.nspname = 'public'
                AND NOT t.tgisinternal
            ORDER BY c.relname, t.tgname
        "#;

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

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

            sql.push_str(&format!("-- Trigger: {} on {}\n", trigger_name, table_name));
            sql.push_str(&definition);
            if !definition.ends_with(';') {
                sql.push_str(";");
            }
            sql.push_str("\n");
        }

        Ok(sql)
    }

    /// Extract foreign key and check constraints
    async fn extract_constraints(&self) -> Result<String> {
        let query = r#"
            SELECT 
                conname AS constraint_name,
                t.relname AS table_name,
                pg_catalog.pg_get_constraintdef(c.oid) AS definition,
                contype::text AS constraint_type
            FROM pg_catalog.pg_constraint c
            JOIN pg_catalog.pg_class t ON c.conrelid = t.oid
            WHERE c.connamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')
                AND contype IN ('f', 'c')  -- foreign keys and check constraints
            ORDER BY t.relname, conname
        "#;

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

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

            let constraint_kind = match constraint_type.as_str() {
                "f" => "FOREIGN KEY",
                "c" => "CHECK",
                _ => "CONSTRAINT",
            };

            sql.push_str(&format!(
                "-- {} constraint: {} on {}\n",
                constraint_kind, constraint_name, table_name
            ));
            sql.push_str(&format!(
                "ALTER TABLE \"{}\" ADD CONSTRAINT \"{}\" {};\n",
                table_name, constraint_name, definition
            ));
        }

        Ok(sql)
    }

    /// Calculate schema statistics
    async fn calculate_schema_statistics(&self) -> Result<SchemaStatistics> {
        let table_count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM pg_tables WHERE schemaname = 'public'",
        )
        .fetch_one(&self.pool)
        .await? as usize;

        let view_count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM pg_views WHERE schemaname = 'public'",
        )
        .fetch_one(&self.pool)
        .await? as usize;

        let index_count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM pg_indexes WHERE schemaname = 'public'",
        )
        .fetch_one(&self.pool)
        .await? as usize;

        let function_count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM pg_proc p 
             JOIN pg_namespace n ON n.oid = p.pronamespace 
             WHERE n.nspname = 'public'",
        )
        .fetch_one(&self.pool)
        .await? as usize;

        let trigger_count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM pg_trigger t 
             JOIN pg_class c ON c.oid = t.tgrelid
             JOIN pg_namespace n ON n.oid = c.relnamespace 
             WHERE n.nspname = 'public' AND NOT t.tgisinternal",
        )
        .fetch_one(&self.pool)
        .await? as usize;

        let composite_type_count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM pg_type t
             JOIN pg_namespace n ON n.oid = t.typnamespace 
             WHERE n.nspname = 'public' AND t.typtype = 'c'",
        )
        .fetch_one(&self.pool)
        .await? as usize;

        let total_columns = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM information_schema.columns 
             WHERE table_schema = 'public'",
        )
        .fetch_one(&self.pool)
        .await? as usize;

        let total_constraints = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM pg_constraint 
             WHERE connamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')",
        )
        .fetch_one(&self.pool)
        .await? as usize;

        Ok(SchemaStatistics {
            table_count,
            view_count,
            index_count,
            function_count,
            trigger_count,
            composite_type_count,
            total_columns,
            total_constraints,
        })
    }

    /// Get database version info
    async fn get_database_version(&self) -> Result<String> {
        let version = sqlx::query_scalar::<_, String>("SELECT version()")
            .fetch_one(&self.pool)
            .await?;
        Ok(version)
    }

    /// Calculate SHA256 checksum of schema
    fn calculate_schema_checksum(schema_ddl: &str) -> String {
        let mut hasher = Sha256::new();

        // Normalize the DDL for consistent checksums
        let normalized = schema_ddl
            .lines()
            .filter(|line| !line.starts_with("--")) // Remove comments
            .map(|line| line.trim())
            .filter(|line| !line.is_empty())
            .collect::<Vec<_>>()
            .join("\n");

        hasher.update(normalized.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// Save baseline migration to file
    pub async fn save_baseline(
        &self,
        baseline: &BaselineMigration,
        output_dir: &str,
    ) -> Result<()> {
        use std::fs;
        use std::path::Path;

        let dir = Path::new(output_dir);
        fs::create_dir_all(dir)?;

        // Save the baseline SQL (always save the monolithic version)
        let sql_path = dir.join(format!("{}.sql", baseline.id));
        fs::write(&sql_path, &baseline.baseline_sql)?;

        // Save the metadata as JSON
        let meta_path = dir.join(format!("{}.json", baseline.id));
        let metadata = serde_json::to_string_pretty(&baseline)?;
        fs::write(&meta_path, metadata)?;

        println!("💾 Baseline saved to:");
        println!("   SQL: {}", sql_path.display());
        println!("   Metadata: {}", meta_path.display());

        Ok(())
    }

    /// Save baseline using a specific migration strategy (generates multiple files based on strategy)
    pub async fn save_baseline_with_strategy(
        &self,
        baseline: &BaselineMigration,
        output_dir: &str,
        strategy: &dyn crate::migrate::MigrationStrategy,
    ) -> Result<()> {
        use std::fs;
        use std::path::Path;

        let dir = Path::new(output_dir);
        fs::create_dir_all(dir)?;

        // Save the metadata as JSON
        let meta_path = dir.join(format!("{}.json", baseline.id));
        let metadata = serde_json::to_string_pretty(&baseline)?;
        fs::write(&meta_path, metadata)?;

        // Parse the baseline SQL into schema changes
        let schema_changes = self
            .parse_baseline_sql_into_changes(&baseline.baseline_sql)
            .await?;

        // Generate migration files using the strategy
        let migration_files = strategy.generate_migrations(schema_changes)?;

        println!(
            "💾 Generating {} migration files using {} strategy:",
            migration_files.len(),
            strategy.name()
        );

        // Save each migration file
        for migration_file in migration_files {
            let file_path = dir.join(&migration_file.filename);

            // Create the migration content with up/down sections
            let content = format!(
                "-- Migration: {}\n-- Generated by Ignis-DB Baseline System\n-- Strategy: {}\n-- Description: {}\n\n-- UP\n{}\n-- DOWN\n{}",
                migration_file.filename.trim_end_matches(".sql"),
                strategy.name(),
                migration_file.description,
                migration_file.up_sql,
                migration_file.down_sql
            );

            fs::write(&file_path, content)?;
            println!("   ✓ {}", file_path.display());
        }

        // Also save the metadata
        println!("   ✓ {}", meta_path.display());

        println!(
            "🎯 Strategy: {} - {}",
            strategy.name(),
            strategy.description()
        );

        Ok(())
    }

    /// Parse baseline SQL into individual schema changes for strategy-based generation
    async fn parse_baseline_sql_into_changes(
        &self,
        baseline_sql: &str,
    ) -> Result<Vec<SchemaChange>> {
        let mut changes = Vec::new();
        let lines: Vec<&str> = baseline_sql.lines().collect();
        let mut i = 0;

        while i < lines.len() {
            let line = lines[i].trim();

            // Skip comments and empty lines
            if line.is_empty() || line.starts_with("--") {
                i += 1;
                continue;
            }

            // Parse CREATE TABLE statements
            if line.to_uppercase().starts_with("CREATE TABLE") {
                let (table_change, lines_consumed) = self.parse_create_table(&lines[i..])?;
                changes.push(table_change);
                i += lines_consumed;
                continue;
            }

            // Parse CREATE INDEX statements
            if line.to_uppercase().starts_with("CREATE") && line.to_uppercase().contains("INDEX") {
                let index_change = self.parse_create_index(line)?;
                changes.push(index_change);
                i += 1;
                continue;
            }

            // Parse CREATE TYPE statements (composite types)
            if line.to_uppercase().starts_with("CREATE TYPE") {
                let (type_change, lines_consumed) = self.parse_create_type(&lines[i..])?;
                changes.push(type_change);
                i += lines_consumed;
                continue;
            }

            // Parse CREATE FUNCTION/PROCEDURE statements
            if line.to_uppercase().starts_with("CREATE")
                && (line.to_uppercase().contains("FUNCTION")
                    || line.to_uppercase().contains("PROCEDURE"))
            {
                let (func_change, lines_consumed) = self.parse_create_function(&lines[i..])?;
                changes.push(func_change);
                i += lines_consumed;
                continue;
            }

            i += 1;
        }

        Ok(changes)
    }

    /// Parse a CREATE TABLE statement
    fn parse_create_table(&self, lines: &[&str]) -> Result<(SchemaChange, usize)> {
        let mut sql_lines = Vec::new();
        let mut lines_consumed = 0;

        // Find the table name
        let first_line = lines[0];
        let table_name = self.extract_table_name(first_line)?;

        // Collect all lines until we find the closing semicolon
        let mut in_table = false;
        for line in lines.iter() {
            lines_consumed += 1;
            sql_lines.push(*line);

            if line.trim().to_uppercase().starts_with("CREATE TABLE") {
                in_table = true;
            }

            if in_table && line.trim().ends_with(';') {
                break;
            }
        }

        let up_sql = sql_lines.join("\n");
        let down_sql = format!("DROP TABLE IF EXISTS \"{}\" CASCADE;", table_name);

        let change = SchemaChange {
            change_type: SchemaChangeType::CreateTable,
            table_name: table_name.clone(),
            object_name: None,
            up_sql,
            down_sql,
            description: format!("Create table {}", table_name),
        };

        Ok((change, lines_consumed))
    }

    /// Parse a CREATE INDEX statement
    fn parse_create_index(&self, line: &str) -> Result<SchemaChange> {
        // Extract index name and table name
        let index_name = self.extract_index_name(line)?;
        let table_name = self.extract_table_name_from_index(line)?;

        let up_sql = line.to_string();
        let down_sql = format!("DROP INDEX IF EXISTS \"{}\";", index_name);

        let change = SchemaChange {
            change_type: SchemaChangeType::CreateIndex,
            table_name,
            object_name: Some(index_name.clone()),
            up_sql,
            down_sql,
            description: format!("Create index {}", index_name),
        };

        Ok(change)
    }

    /// Parse a CREATE TYPE statement
    fn parse_create_type(&self, lines: &[&str]) -> Result<(SchemaChange, usize)> {
        let mut sql_lines = Vec::new();
        let mut lines_consumed = 0;

        // Find the type name
        let first_line = lines[0];
        let type_name = self.extract_type_name(first_line)?;

        // Collect all lines until we find the closing semicolon
        for line in lines.iter() {
            lines_consumed += 1;
            sql_lines.push(*line);

            if line.trim().ends_with(';') {
                break;
            }
        }

        let up_sql = sql_lines.join("\n");
        let down_sql = format!("DROP TYPE IF EXISTS \"{}\" CASCADE;", type_name);

        let change = SchemaChange {
            change_type: SchemaChangeType::CreateCompositeType,
            table_name: "".to_string(), // Types don't belong to tables
            object_name: Some(type_name.clone()),
            up_sql,
            down_sql,
            description: format!("Create composite type {}", type_name),
        };

        Ok((change, lines_consumed))
    }

    /// Parse a CREATE FUNCTION/PROCEDURE statement
    fn parse_create_function(&self, lines: &[&str]) -> Result<(SchemaChange, usize)> {
        let mut sql_lines = Vec::new();
        let mut lines_consumed = 0;
        let mut dollar_tag = None;

        // Find the function name
        let first_line = lines[0];
        let function_name = self.extract_function_name(first_line)?;

        // Collect all lines until we find the closing $$ or semicolon
        for line in lines.iter() {
            lines_consumed += 1;
            sql_lines.push(*line);

            // Handle dollar-quoted strings
            if let Some(tag) = &dollar_tag {
                if line.trim() == *tag {
                    dollar_tag = None;
                }
            } else if line.trim().starts_with("$") && line.trim().ends_with("$") {
                dollar_tag = Some(line.trim().to_string());
            } else if line.trim().ends_with(';') && dollar_tag.is_none() {
                break;
            }
        }

        let up_sql = sql_lines.join("\n");
        let down_sql = format!("DROP FUNCTION IF EXISTS \"{}\" CASCADE;", function_name);

        let change = SchemaChange {
            change_type: SchemaChangeType::CreateCompositeType, // We'll use this for functions too
            table_name: "".to_string(),
            object_name: Some(function_name.clone()),
            up_sql,
            down_sql,
            description: format!("Create function {}", function_name),
        };

        Ok((change, lines_consumed))
    }

    /// Extract table name from CREATE TABLE statement
    fn extract_table_name(&self, line: &str) -> Result<String> {
        let parts: Vec<&str> = line.split_whitespace().collect();
        for (i, part) in parts.iter().enumerate() {
            if part.to_uppercase() == "TABLE" && i + 1 < parts.len() {
                let table_name = parts[i + 1].trim_matches('"').trim_matches('(').to_string();
                return Ok(table_name);
            }
        }
        Err(anyhow::anyhow!(
            "Could not extract table name from: {}",
            line
        ))
    }

    /// Extract index name from CREATE INDEX statement
    fn extract_index_name(&self, line: &str) -> Result<String> {
        let parts: Vec<&str> = line.split_whitespace().collect();
        for (i, part) in parts.iter().enumerate() {
            if part.to_uppercase() == "INDEX" && i + 1 < parts.len() {
                let index_name = parts[i + 1].trim_matches('"').to_string();
                return Ok(index_name);
            }
        }
        Err(anyhow::anyhow!(
            "Could not extract index name from: {}",
            line
        ))
    }

    /// Extract table name from CREATE INDEX statement
    fn extract_table_name_from_index(&self, line: &str) -> Result<String> {
        if let Some(on_pos) = line.to_uppercase().find(" ON ") {
            let after_on = &line[on_pos + 4..];
            let table_name = after_on
                .split_whitespace()
                .next()
                .unwrap_or("")
                .trim_matches('"')
                .trim_matches('(')
                .to_string();
            return Ok(table_name);
        }
        Err(anyhow::anyhow!(
            "Could not extract table name from index: {}",
            line
        ))
    }

    /// Extract type name from CREATE TYPE statement
    fn extract_type_name(&self, line: &str) -> Result<String> {
        let parts: Vec<&str> = line.split_whitespace().collect();
        for (i, part) in parts.iter().enumerate() {
            if part.to_uppercase() == "TYPE" && i + 1 < parts.len() {
                let type_name = parts[i + 1].trim_matches('"').to_string();
                return Ok(type_name);
            }
        }
        Err(anyhow::anyhow!(
            "Could not extract type name from: {}",
            line
        ))
    }

    /// Extract function name from CREATE FUNCTION statement
    fn extract_function_name(&self, line: &str) -> Result<String> {
        let parts: Vec<&str> = line.split_whitespace().collect();
        for (i, part) in parts.iter().enumerate() {
            if (part.to_uppercase() == "FUNCTION" || part.to_uppercase() == "PROCEDURE")
                && i + 1 < parts.len()
            {
                let func_name = parts[i + 1]
                    .split('(')
                    .next()
                    .unwrap_or("")
                    .trim_matches('"')
                    .to_string();
                return Ok(func_name);
            }
        }
        Err(anyhow::anyhow!(
            "Could not extract function name from: {}",
            line
        ))
    }

    /// Apply baseline to migration tracking table
    pub async fn apply_baseline(&self, baseline: &BaselineMigration) -> Result<()> {
        // Ensure migration table exists
        self.ensure_migration_table().await?;

        // Mark baseline as applied
        let query = r#"
            INSERT INTO __ignis_migrations (name, checksum, applied_at, is_baseline)
            VALUES ($1, $2, $3, true)
            ON CONFLICT (name) DO NOTHING
        "#;

        sqlx::query(query)
            .bind(&baseline.id)
            .bind(&baseline.schema_checksum)
            .bind(baseline.created_at)
            .execute(&self.pool)
            .await?;

        println!("✅ Baseline marked as applied in migration tracking table");

        Ok(())
    }

    /// Ensure migration tracking table exists with baseline support
    async fn ensure_migration_table(&self) -> Result<()> {
        let query = r#"
            CREATE TABLE IF NOT EXISTS __ignis_migrations (
                id SERIAL PRIMARY KEY,
                name VARCHAR(255) NOT NULL UNIQUE,
                checksum VARCHAR(64) NOT NULL,
                applied_at TIMESTAMPTZ DEFAULT NOW(),
                is_baseline BOOLEAN DEFAULT false
            )
        "#;

        sqlx::query(query).execute(&self.pool).await?;
        Ok(())
    }

    /// Verify if a baseline already exists
    pub async fn has_baseline(&self) -> Result<bool> {
        self.ensure_migration_table().await?;

        let count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM __ignis_migrations WHERE is_baseline = true",
        )
        .fetch_one(&self.pool)
        .await?;

        Ok(count > 0)
    }

    /// Get existing baseline information
    pub async fn get_baseline_info(&self) -> Result<Option<(String, String, DateTime<Utc>)>> {
        self.ensure_migration_table().await?;

        let row = sqlx::query(
            "SELECT name, checksum, applied_at 
             FROM __ignis_migrations 
             WHERE is_baseline = true 
             ORDER BY applied_at DESC 
             LIMIT 1",
        )
        .fetch_optional(&self.pool)
        .await?;

        Ok(row.map(|r| (r.get("name"), r.get("checksum"), r.get("applied_at"))))
    }
}