Skip to main content

ignis_db/database/
postgres.rs

1//! PostgreSQL database implementation
2//!
3//! This module provides the PostgreSQL-specific implementation of the database traits.
4
5use super::traits::*;
6use super::{DatabaseConfig, DatabaseType};
7use crate::migrate::Migration;
8use crate::schema::{CompositeType, Grant, Index, Role, Table, View};
9use anyhow::Result;
10use sqlx::{postgres::PgConnectOptions, PgPool, Row};
11use std::collections::HashMap;
12use std::str::FromStr;
13use std::sync::Arc;
14
15/// PostgreSQL database implementation
16pub struct PostgreSQL {
17    name: String,
18    _pool: Arc<sqlx::PgPool>,
19    type_mapping: PostgreSQLTypeMapping,
20    sql_generator: PostgreSQLSqlGenerator,
21    introspector: PostgreSQLIntrospector,
22    connection_manager: PostgreSQLConnectionManager,
23    migration_manager: PostgreSQLMigrationManager,
24}
25
26impl PostgreSQL {
27    /// Create a new PostgreSQL database instance
28    pub fn new(name: impl Into<String>) -> Self {
29        let pool = Arc::new(PgPool::connect_lazy("postgresql://mock").unwrap());
30        Self {
31            name: name.into(),
32            _pool: pool.clone(),
33            type_mapping: PostgreSQLTypeMapping,
34            sql_generator: PostgreSQLSqlGenerator,
35            introspector: PostgreSQLIntrospector { pool: pool.clone() },
36            connection_manager: PostgreSQLConnectionManager,
37            migration_manager: PostgreSQLMigrationManager::new(pool),
38        }
39    }
40
41    /// Create a new PostgreSQL database instance with a pool
42    pub fn with_pool(name: impl Into<String>, pool: Arc<PgPool>) -> Self {
43        Self {
44            name: name.into(),
45            _pool: pool.clone(),
46            type_mapping: PostgreSQLTypeMapping,
47            sql_generator: PostgreSQLSqlGenerator,
48            introspector: PostgreSQLIntrospector { pool: pool.clone() },
49            connection_manager: PostgreSQLConnectionManager,
50            migration_manager: PostgreSQLMigrationManager::new(pool),
51        }
52    }
53
54    /// Get the connection pool
55    pub fn pool(&self) -> &Arc<PgPool> {
56        &self._pool
57    }
58
59    /// Generate SQL for creating a table
60    pub fn create_table_sql(&self, table: &Table) -> String {
61        self.sql_generator.create_table_sql(table)
62    }
63}
64
65impl Database for PostgreSQL {
66    fn database_type(&self) -> DatabaseType {
67        DatabaseType::PostgreSQL
68    }
69
70    fn name(&self) -> &str {
71        &self.name
72    }
73
74    fn type_mapping(&self) -> &dyn TypeMapping {
75        &self.type_mapping
76    }
77
78    fn sql_generator(&self) -> &dyn SqlGenerator {
79        &self.sql_generator
80    }
81
82    fn introspector(&self) -> &dyn Introspector {
83        &self.introspector
84    }
85
86    fn connection_manager(&self) -> &dyn ConnectionManager {
87        &self.connection_manager
88    }
89
90    fn migration_manager(&self) -> &dyn MigrationManager {
91        &self.migration_manager
92    }
93}
94
95/// PostgreSQL type mapping implementation
96pub struct PostgreSQLTypeMapping;
97
98impl TypeMapping for PostgreSQLTypeMapping {
99    fn rust_to_sql_type(&self, rust_type: &str) -> String {
100        match rust_type {
101            "String" => "TEXT".to_string(),
102            "i32" => "INTEGER".to_string(),
103            "i64" => "BIGINT".to_string(),
104            "f32" => "REAL".to_string(),
105            "f64" => "DOUBLE PRECISION".to_string(),
106            "bool" => "BOOLEAN".to_string(),
107            "chrono::DateTime<chrono::Utc>" => "TIMESTAMPTZ".to_string(),
108            "chrono::NaiveDateTime" => "TIMESTAMP".to_string(),
109            "chrono::NaiveDate" => "DATE".to_string(),
110            "chrono::NaiveTime" => "TIME".to_string(),
111            "uuid::Uuid" => "UUID".to_string(),
112            "rust_decimal::Decimal" => "DECIMAL".to_string(),
113            "serde_json::Value" => "JSONB".to_string(),
114            "Vec<u8>" => "BYTEA".to_string(),
115            _ => format!("TEXT"), // Default fallback
116        }
117    }
118
119    fn sql_to_rust_type(&self, sql_type: &str) -> String {
120        match sql_type.to_uppercase().as_str() {
121            "TEXT" | "VARCHAR" | "CHAR" => "String".to_string(),
122            "INTEGER" | "INT" | "INT4" => "i32".to_string(),
123            "BIGINT" | "INT8" => "i64".to_string(),
124            "REAL" | "FLOAT4" => "f32".to_string(),
125            "DOUBLE PRECISION" | "FLOAT8" => "f64".to_string(),
126            "BOOLEAN" | "BOOL" => "bool".to_string(),
127            "TIMESTAMPTZ" => "chrono::DateTime<chrono::Utc>".to_string(),
128            "TIMESTAMP" => "chrono::NaiveDateTime".to_string(),
129            "DATE" => "chrono::NaiveDate".to_string(),
130            "TIME" => "chrono::NaiveTime".to_string(),
131            "UUID" => "uuid::Uuid".to_string(),
132            "DECIMAL" | "NUMERIC" => "rust_decimal::Decimal".to_string(),
133            "JSONB" | "JSON" => "serde_json::Value".to_string(),
134            "BYTEA" => "Vec<u8>".to_string(),
135            _ => "String".to_string(), // Default fallback
136        }
137    }
138
139    fn default_value(&self, sql_type: &str) -> Option<String> {
140        match sql_type.to_uppercase().as_str() {
141            "BOOLEAN" | "BOOL" => Some("false".to_string()),
142            "INTEGER" | "INT" | "INT4" | "BIGINT" | "INT8" => Some("0".to_string()),
143            "REAL" | "FLOAT4" | "DOUBLE PRECISION" | "FLOAT8" => Some("0.0".to_string()),
144            "TIMESTAMPTZ" | "TIMESTAMP" => Some("NOW()".to_string()),
145            "DATE" => Some("CURRENT_DATE".to_string()),
146            "TIME" => Some("CURRENT_TIME".to_string()),
147            "UUID" => Some("gen_random_uuid()".to_string()),
148            _ => None,
149        }
150    }
151
152    fn supports_auto_increment(&self, sql_type: &str) -> bool {
153        matches!(sql_type.to_uppercase().as_str(), "SERIAL" | "BIGSERIAL")
154    }
155
156    fn max_string_length(&self, sql_type: &str) -> Option<usize> {
157        match sql_type.to_uppercase().as_str() {
158            "VARCHAR" => Some(65535), // PostgreSQL VARCHAR limit
159            "CHAR" => Some(255),      // PostgreSQL CHAR limit
160            _ => None,
161        }
162    }
163}
164
165/// PostgreSQL SQL generator implementation
166pub struct PostgreSQLSqlGenerator;
167
168impl SqlGenerator for PostgreSQLSqlGenerator {
169    fn create_table_sql(&self, table: &Table) -> String {
170        let table_name = if let Some(schema) = &table.schema {
171            format!("\"{}\".\"{}\"", schema, table.name)
172        } else {
173            format!("\"{}\"", table.name)
174        };
175        let mut sql = format!("CREATE TABLE {} (\n", table_name);
176
177        for (i, column) in table.columns.iter().enumerate() {
178            if i > 0 {
179                sql.push_str(",\n");
180            }
181            sql.push_str(&format!(
182                "    \"{}\" {}",
183                column.name,
184                column.column_type.to_sql()
185            ));
186
187            if !column.nullable {
188                sql.push_str(" NOT NULL");
189            }
190
191            if column.unique {
192                sql.push_str(" UNIQUE");
193            }
194
195            if let Some(default) = &column.default {
196                sql.push_str(&format!(" DEFAULT {}", default));
197            }
198        }
199
200        if let Some(primary_key) = &table.primary_key {
201            sql.push_str(&format!(",\n    PRIMARY KEY (\"{}\")", primary_key));
202        }
203
204        sql.push_str("\n);");
205        sql
206    }
207
208    fn create_view_sql(&self, view: &View) -> String {
209        if view.materialized {
210            format!(
211                "CREATE MATERIALIZED VIEW \"{}\" AS {}",
212                view.name,
213                view.ddl.as_ref().unwrap_or(&"".to_string())
214            )
215        } else {
216            format!(
217                "CREATE VIEW \"{}\" AS {}",
218                view.name,
219                view.ddl.as_ref().unwrap_or(&"".to_string())
220            )
221        }
222    }
223
224    fn create_index_sql(&self, index: &Index) -> String {
225        let unique = if index.unique { "UNIQUE " } else { "" };
226        let columns = index.columns.join("\", \"");
227        format!(
228            "CREATE {}INDEX \"{}\" ON \"{}\" (\"{}\")",
229            unique, index.name, "table_name", columns
230        )
231    }
232
233    fn create_type_sql(&self, composite_type: &CompositeType) -> String {
234        let mut sql = format!("CREATE TYPE \"{}\" AS (", composite_type.name);
235
236        for (i, field) in composite_type.fields.iter().enumerate() {
237            if i > 0 {
238                sql.push_str(", ");
239            }
240            sql.push_str(&format!("\"{}\" {}", field.name, field.field_type));
241        }
242
243        sql.push_str(");");
244        sql
245    }
246
247    fn create_schema_sql(&self, schema_name: &str) -> String {
248        format!("CREATE SCHEMA IF NOT EXISTS \"{}\";", schema_name)
249    }
250
251    fn alter_table_sql(&self, table: &Table, changes: &[String]) -> String {
252        let mut sql = format!("ALTER TABLE \"{}\"", table.name);
253
254        for (i, change) in changes.iter().enumerate() {
255            if i > 0 {
256                sql.push_str(",");
257            }
258            sql.push_str(&format!(" {}", change));
259        }
260
261        sql.push_str(";");
262        sql
263    }
264
265    fn drop_table_sql(&self, table_name: &str) -> String {
266        format!("DROP TABLE IF EXISTS \"{}\" CASCADE;", table_name)
267    }
268
269    fn drop_view_sql(&self, view_name: &str) -> String {
270        format!("DROP VIEW IF EXISTS \"{}\" CASCADE;", view_name)
271    }
272
273    fn drop_index_sql(&self, index_name: &str) -> String {
274        format!("DROP INDEX IF EXISTS \"{}\";", index_name)
275    }
276
277    fn insert_sql(&self, table_name: &str, columns: &[String], values: &[String]) -> String {
278        let columns_str = columns
279            .iter()
280            .map(|c| format!("\"{}\"", c))
281            .collect::<Vec<_>>()
282            .join(", ");
283        let values_str = values.join(", ");
284        format!(
285            "INSERT INTO \"{}\" ({}) VALUES ({});",
286            table_name, columns_str, values_str
287        )
288    }
289
290    fn update_sql(&self, table_name: &str, set_clause: &str, where_clause: &str) -> String {
291        format!(
292            "UPDATE \"{}\" SET {} WHERE {};",
293            table_name, set_clause, where_clause
294        )
295    }
296
297    fn delete_sql(&self, table_name: &str, where_clause: &str) -> String {
298        format!("DELETE FROM \"{}\" WHERE {};", table_name, where_clause)
299    }
300
301    fn select_sql(
302        &self,
303        table_name: &str,
304        columns: &[String],
305        where_clause: Option<&str>,
306    ) -> String {
307        let columns_str = if columns.is_empty() {
308            "*".to_string()
309        } else {
310            columns
311                .iter()
312                .map(|c| format!("\"{}\"", c))
313                .collect::<Vec<_>>()
314                .join(", ")
315        };
316
317        let mut sql = format!("SELECT {} FROM \"{}\"", columns_str, table_name);
318
319        if let Some(where_clause) = where_clause {
320            sql.push_str(&format!(" WHERE {}", where_clause));
321        }
322
323        sql.push_str(";");
324        sql
325    }
326
327    fn quote_identifier(&self, identifier: &str) -> String {
328        format!("\"{}\"", identifier)
329    }
330
331    fn quote_string(&self, value: &str) -> String {
332        format!("'{}'", value.replace("'", "''"))
333    }
334
335    fn current_timestamp_function(&self) -> &str {
336        "NOW()"
337    }
338
339    fn auto_increment_keyword(&self) -> &str {
340        "SERIAL"
341    }
342
343    fn create_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
344        guc.to_sql()
345    }
346
347    fn reset_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
348        guc.to_reset_sql()
349    }
350
351    fn get_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
352        guc.get_value_sql()
353    }
354
355    fn list_guc_settings_sql(&self) -> String {
356        "SELECT name, setting, context, unit, short_desc FROM pg_settings ORDER BY name;"
357            .to_string()
358    }
359
360    fn set_jwt_context_sql(
361        &self,
362        user_id: &str,
363        tenant_id: Option<&str>,
364        role: Option<&str>,
365    ) -> String {
366        let mut sql = format!("SET jwt.user_id = '{}';", user_id);
367        if let Some(tenant) = tenant_id {
368            sql.push_str(&format!("\nSET jwt.tenant_id = '{}';", tenant));
369        }
370        if let Some(role) = role {
371            sql.push_str(&format!("\nSET jwt.role = '{}';", role));
372        }
373        sql
374    }
375
376    fn clear_jwt_context_sql(&self) -> String {
377        "RESET jwt.user_id;\nRESET jwt.tenant_id;\nRESET jwt.role;".to_string()
378    }
379}
380
381impl PostgreSQLSqlGenerator {
382    /// Create RLS policy SQL
383    pub fn create_policy_sql(&self, policy: &crate::schema::Policy) -> String {
384        policy.to_sql()
385    }
386
387    /// Create RLS enable SQL for a table
388    pub fn enable_rls_sql(&self, table_name: &str, schema: Option<&str>) -> String {
389        let full_name = if let Some(schema) = schema {
390            format!("\"{}\".\"{}\"", schema, table_name)
391        } else {
392            format!("\"{}\"", table_name)
393        };
394        format!("ALTER TABLE {} ENABLE ROW LEVEL SECURITY;", full_name)
395    }
396
397    /// Create RLS disable SQL for a table
398    pub fn disable_rls_sql(&self, table_name: &str, schema: Option<&str>) -> String {
399        let full_name = if let Some(schema) = schema {
400            format!("\"{}\".\"{}\"", schema, table_name)
401        } else {
402            format!("\"{}\"", table_name)
403        };
404        format!("ALTER TABLE {} DISABLE ROW LEVEL SECURITY;", full_name)
405    }
406
407    /// Drop policy SQL
408    pub fn drop_policy_sql(&self, policy: &crate::schema::Policy) -> String {
409        policy.to_drop_sql()
410    }
411
412    /// Create extension SQL
413    pub fn create_extension_sql(&self, extension: &crate::schema::Extension) -> String {
414        extension.to_sql()
415    }
416
417    /// Drop extension SQL
418    pub fn drop_extension_sql(&self, extension: &crate::schema::Extension) -> String {
419        extension.to_drop_sql()
420    }
421
422    /// Check if extension exists SQL
423    pub fn extension_exists_sql(&self, extension_name: &str) -> String {
424        format!(
425            "SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname = '{}');",
426            extension_name
427        )
428    }
429
430    /// List installed extensions SQL
431    pub fn list_extensions_sql(&self) -> String {
432        "SELECT extname, extversion, nspname as schema FROM pg_extension e JOIN pg_namespace n ON e.extnamespace = n.oid ORDER BY extname;".to_string()
433    }
434
435    /// Create GUC setting SQL
436    pub fn create_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
437        guc.to_sql()
438    }
439
440    /// Reset GUC setting SQL
441    pub fn reset_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
442        guc.to_reset_sql()
443    }
444
445    /// Get GUC setting value SQL
446    pub fn get_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
447        guc.get_value_sql()
448    }
449
450    /// List all GUC settings SQL
451    pub fn list_guc_settings_sql(&self) -> String {
452        "SELECT name, setting, context, unit, short_desc FROM pg_settings ORDER BY name;"
453            .to_string()
454    }
455
456    /// Set JWT context SQL
457    pub fn set_jwt_context_sql(
458        &self,
459        user_id: &str,
460        tenant_id: Option<&str>,
461        role: Option<&str>,
462    ) -> String {
463        let mut sql = format!("SET jwt.claims.user_id = '{}';", user_id);
464
465        if let Some(tenant) = tenant_id {
466            sql.push_str(&format!("\nSET jwt.claims.tenant_id = '{}';", tenant));
467        }
468
469        if let Some(user_role) = role {
470            sql.push_str(&format!("\nSET jwt.claims.role = '{}';", user_role));
471        }
472
473        sql
474    }
475
476    /// Clear JWT context SQL
477    pub fn clear_jwt_context_sql(&self) -> String {
478        "RESET jwt.claims.user_id;\nRESET jwt.claims.tenant_id;\nRESET jwt.claims.role;".to_string()
479    }
480}
481
482/// PostgreSQL introspector implementation
483pub struct PostgreSQLIntrospector {
484    pool: Arc<PgPool>,
485}
486
487impl PostgreSQLIntrospector {
488    pub fn new(pool: Arc<PgPool>) -> Self {
489        Self { pool }
490    }
491
492    /// Map PostgreSQL data type to Ignis-DB ColumnType
493    fn map_pg_type_to_ignis_type(
494        &self,
495        pg_type: &str,
496        _is_nullable: bool,
497        max_length: Option<i32>,
498        precision: Option<i32>,
499        scale: Option<i32>,
500    ) -> crate::schema::ColumnType {
501        match pg_type.to_lowercase().as_str() {
502            "integer" | "int" | "int4" => crate::schema::ColumnType::Int4,
503            "bigint" | "int8" => crate::schema::ColumnType::Int8,
504            "smallint" | "int2" => crate::schema::ColumnType::Int2,
505            "text" => crate::schema::ColumnType::Text,
506            "varchar" | "character varying" => {
507                if let Some(length) = max_length {
508                    crate::schema::ColumnType::Varchar(Some(length as usize))
509                } else {
510                    crate::schema::ColumnType::Varchar(None)
511                }
512            }
513            "char" | "character" => crate::schema::ColumnType::Char,
514            "boolean" | "bool" => crate::schema::ColumnType::Bool,
515            "timestamp with time zone" | "timestamptz" => crate::schema::ColumnType::Timestamptz,
516            "timestamp without time zone" | "timestamp" => crate::schema::ColumnType::Timestamptz,
517            "date" => crate::schema::ColumnType::Date,
518            "time" => crate::schema::ColumnType::Time,
519            "uuid" => crate::schema::ColumnType::Uuid,
520            "numeric" | "decimal" => match (precision, scale) {
521                (Some(p), Some(s)) => {
522                    crate::schema::ColumnType::Numeric(Some(p as usize), Some(s as usize))
523                }
524                (Some(p), None) => crate::schema::ColumnType::Numeric(Some(p as usize), None),
525                (None, Some(s)) => crate::schema::ColumnType::Numeric(None, Some(s as usize)),
526                (None, None) => crate::schema::ColumnType::Numeric(None, None),
527            },
528            "jsonb" => crate::schema::ColumnType::Jsonb,
529            "json" => crate::schema::ColumnType::Json,
530            "bytea" => crate::schema::ColumnType::Text, // Use Text for bytea for now
531            "real" | "float4" => crate::schema::ColumnType::Numeric(None, None), // Use Numeric for float
532            "double precision" | "float8" => crate::schema::ColumnType::Numeric(None, None), // Use Numeric for double
533            // Handle arrays: integer[] -> Array(Box<ColumnType::Int4>)
534            array_type if array_type.ends_with("[]") => {
535                let base_type = &array_type[..array_type.len() - 2];
536                let base_column_type =
537                    self.map_pg_type_to_ignis_type(base_type, false, None, None, None);
538                crate::schema::ColumnType::Array(Box::new(base_column_type))
539            }
540            // Handle composite types and other custom types
541            custom => crate::schema::ColumnType::Custom(custom.to_string()),
542        }
543    }
544}
545
546impl Introspector for PostgreSQLIntrospector {
547    fn get_tables(&self) -> Result<Vec<Table>> {
548        // For now, return mock data to avoid async complexity
549        // In a real implementation, this would use the existing introspection logic
550        println!("🔍 PostgreSQL introspection: Getting all tables");
551
552        // Return mock data for demonstration
553        let mut tables = Vec::new();
554        let mut table = Table::new("users");
555        table = table.add_column(
556            crate::schema::Column::new("id", crate::schema::ColumnType::Int4).not_null(),
557        );
558        table = table.add_column(
559            crate::schema::Column::new("name", crate::schema::ColumnType::Varchar(Some(255)))
560                .not_null(),
561        );
562        table = table.add_column(
563            crate::schema::Column::new("email", crate::schema::ColumnType::Varchar(Some(255)))
564                .not_null(),
565        );
566        tables.push(table);
567
568        Ok(tables)
569    }
570
571    fn get_table(&self, table_name: &str) -> Result<Option<Table>> {
572        // Use the existing introspection logic for a specific table
573        let rt = tokio::runtime::Handle::try_current()
574            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
575
576        rt.block_on(async {
577            let query = r#"
578                SELECT 
579                    t.table_name,
580                    c.column_name,
581                    c.data_type,
582                    c.is_nullable = 'YES' as is_nullable,
583                    c.column_default,
584                    c.character_maximum_length,
585                    c.numeric_precision,
586                    c.numeric_scale
587                FROM information_schema.tables t
588                JOIN information_schema.columns c ON t.table_name = c.table_name
589                WHERE t.table_schema = 'public' 
590                    AND t.table_type = 'BASE TABLE'
591                    AND t.table_name = $1
592                ORDER BY c.ordinal_position
593            "#;
594
595            let rows = sqlx::query(query)
596                .bind(table_name)
597                .fetch_all(&*self.pool)
598                .await?;
599
600            if rows.is_empty() {
601                return Ok(None);
602            }
603
604            // Build table from rows
605            let mut table = Table::new(table_name);
606            for row in rows {
607                let column_name: String = row.get("column_name");
608                let data_type: String = row.get("data_type");
609                let is_nullable: bool = row.get("is_nullable");
610                let column_default: Option<String> = row.get("column_default");
611                let max_length: Option<i32> = row.get("character_maximum_length");
612                let precision: Option<i32> = row.get("numeric_precision");
613                let scale: Option<i32> = row.get("numeric_scale");
614
615                let column_type = self.map_pg_type_to_ignis_type(
616                    &data_type,
617                    is_nullable,
618                    max_length,
619                    precision,
620                    scale,
621                );
622
623                let mut column = crate::schema::Column::new(&column_name, column_type);
624                if !is_nullable {
625                    column = column.not_null();
626                }
627                if let Some(default) = column_default {
628                    column = column.default(default);
629                }
630
631                table = table.add_column(column);
632            }
633
634            Ok(Some(table))
635        })
636    }
637
638    fn get_views(&self) -> Result<Vec<View>> {
639        let rt = tokio::runtime::Handle::try_current()
640            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
641
642        rt.block_on(async {
643            let mut views = Vec::new();
644
645            // Introspect regular views
646            let regular_views_query = r#"
647                SELECT 
648                    viewname as name,
649                    definition
650                FROM pg_views
651                WHERE schemaname = 'public'
652                ORDER BY viewname
653            "#;
654
655            let regular_rows = sqlx::query(regular_views_query)
656                .fetch_all(&*self.pool)
657                .await?;
658            for row in regular_rows {
659                let name: String = row.get("name");
660                let definition: String = row.get("definition");
661
662                let mut view = crate::schema::View::new(&name);
663                view.set_ddl(&definition);
664                view.set_materialized(false);
665                views.push(view);
666            }
667
668            // Introspect materialized views
669            let materialized_views_query = r#"
670                SELECT 
671                    matviewname as name,
672                    definition
673                FROM pg_matviews
674                WHERE schemaname = 'public'
675                ORDER BY matviewname
676            "#;
677
678            let materialized_rows = sqlx::query(materialized_views_query)
679                .fetch_all(&*self.pool)
680                .await?;
681            for row in materialized_rows {
682                let name: String = row.get("name");
683                let definition: String = row.get("definition");
684
685                let mut view = crate::schema::View::new(&name);
686                view.set_ddl(&definition);
687                view.set_materialized(true);
688                views.push(view);
689            }
690
691            Ok(views)
692        })
693    }
694
695    fn get_view(&self, view_name: &str) -> Result<Option<View>> {
696        let views = self.get_views()?;
697        Ok(views.into_iter().find(|v| v.name == view_name))
698    }
699
700    fn get_indexes(&self) -> Result<Vec<Index>> {
701        let rt = tokio::runtime::Handle::try_current()
702            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
703
704        rt.block_on(async {
705            let query = r#"
706                SELECT 
707                    indexname as name,
708                    tablename as table_name,
709                    indexdef as definition
710                FROM pg_indexes
711                WHERE schemaname = 'public'
712                ORDER BY indexname
713            "#;
714
715            let rows = sqlx::query(query).fetch_all(&*self.pool).await?;
716            let mut indexes = Vec::new();
717
718            for row in rows {
719                let name: String = row.get("name");
720                let table_name: String = row.get("table_name");
721                let definition: String = row.get("definition");
722
723                // Parse the index definition to extract properties
724                let is_unique = definition.contains("UNIQUE");
725                let columns = vec![table_name]; // For now, just use table name as placeholder
726
727                let index = crate::schema::Index::new(&name, columns, is_unique);
728
729                indexes.push(index);
730            }
731
732            Ok(indexes)
733        })
734    }
735
736    fn get_table_indexes(&self, table_name: &str) -> Result<Vec<Index>> {
737        let query = r#"
738            SELECT 
739                indexname as name,
740                indexdef as definition
741            FROM pg_indexes
742            WHERE schemaname = 'public'
743                AND tablename = $1
744            ORDER BY indexname
745        "#;
746
747        let rt = tokio::runtime::Handle::try_current()
748            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
749
750        rt.block_on(async {
751            let rows = sqlx::query(query)
752                .bind(table_name)
753                .fetch_all(&*self.pool)
754                .await?;
755
756            let mut indexes = Vec::new();
757
758            for row in rows {
759                let name: String = row.get("name");
760                let definition: String = row.get("definition");
761
762                // Parse the index definition to extract properties
763                let is_unique = definition.contains("UNIQUE");
764                let columns = vec![table_name.to_string()]; // For now, just use table name as placeholder
765
766                let index = crate::schema::Index::new(&name, columns, is_unique);
767
768                indexes.push(index);
769            }
770
771            Ok(indexes)
772        })
773    }
774
775    fn get_composite_types(&self) -> Result<Vec<CompositeType>> {
776        let rt = tokio::runtime::Handle::try_current()
777            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
778
779        rt.block_on(async {
780            let query = r#"
781                SELECT 
782                    t.typname as name,
783                    a.attname as field_name,
784                    pg_catalog.format_type(a.atttypid, a.atttypmod) as field_type,
785                    a.attnotnull as is_not_null
786                FROM pg_type t
787                JOIN pg_class c ON c.oid = t.typrelid
788                JOIN pg_attribute a ON a.attrelid = c.oid
789                WHERE t.typtype = 'c' 
790                    AND c.relkind = 'c'
791                    AND a.attnum > 0
792                    AND a.attisdropped = false
793                ORDER BY t.typname, a.attnum
794            "#;
795
796            let rows = sqlx::query(query).fetch_all(&*self.pool).await?;
797            let mut composite_types = Vec::new();
798            let mut current_type: Option<CompositeType> = None;
799            let mut current_fields: Vec<crate::schema::CompositeField> = Vec::new();
800
801            for row in rows {
802                let type_name: String = row.get("name");
803                let field_name: String = row.get("field_name");
804                let field_type: String = row.get("field_type");
805                let is_not_null: bool = row.get("is_not_null");
806
807                if let Some(ref composite_type) = current_type {
808                    if composite_type.name != type_name {
809                        // Finish current type
810                        let mut composite_type = composite_type.clone();
811                        for field in current_fields.drain(..) {
812                            composite_type = composite_type.with_field(
813                                field.name,
814                                field.field_type,
815                                field.nullable,
816                            );
817                        }
818                        composite_types.push(composite_type);
819
820                        // Start new type
821                        current_type = Some(CompositeType::new(&type_name));
822                    }
823                } else {
824                    current_type = Some(CompositeType::new(&type_name));
825                }
826
827                // Create field from introspected data
828                let field = crate::schema::CompositeField {
829                    name: field_name,
830                    field_type,
831                    nullable: !is_not_null,
832                };
833
834                current_fields.push(field);
835            }
836
837            // Don't forget the last type
838            if let Some(composite_type) = current_type {
839                let mut composite_type = composite_type;
840                for field in current_fields {
841                    composite_type =
842                        composite_type.with_field(field.name, field.field_type, field.nullable);
843                }
844                composite_types.push(composite_type);
845            }
846
847            Ok(composite_types)
848        })
849    }
850
851    fn get_composite_type(&self, type_name: &str) -> Result<Option<CompositeType>> {
852        let composite_types = self.get_composite_types()?;
853        Ok(composite_types.into_iter().find(|t| t.name == type_name))
854    }
855
856    fn get_roles(&self) -> Result<Vec<Role>> {
857        let rt = tokio::runtime::Handle::try_current()
858            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
859
860        rt.block_on(async {
861            let query = r#"
862                SELECT 
863                    rolname as name,
864                    rolcanlogin as can_login,
865                    rolsuper as is_superuser,
866                    rolcreatedb as can_create_db,
867                    rolcreaterole as can_create_role
868                FROM pg_roles
869                WHERE rolname NOT IN ('postgres', 'pg_signal_backend')
870                ORDER BY rolname
871            "#;
872
873            let rows = sqlx::query(query).fetch_all(&*self.pool).await?;
874            let mut roles = Vec::new();
875
876            for row in rows {
877                let name: String = row.get("name");
878                let can_login: bool = row.get("can_login");
879                let is_superuser: bool = row.get("is_superuser");
880                let can_create_db: bool = row.get("can_create_db");
881                let can_create_role: bool = row.get("can_create_role");
882
883                let role = crate::schema::Role::new(&name)
884                    .with_login(can_login)
885                    .with_superuser(is_superuser)
886                    .with_createdb(can_create_db)
887                    .with_createrole(can_create_role);
888
889                roles.push(role);
890            }
891
892            Ok(roles)
893        })
894    }
895
896    fn get_grants(&self) -> Result<Vec<Grant>> {
897        let rt = tokio::runtime::Handle::try_current()
898            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
899
900        rt.block_on(async {
901            let query = r#"
902                SELECT 
903                    grantee,
904                    table_name,
905                    privilege_type,
906                    is_grantable
907                FROM information_schema.role_table_grants
908                WHERE table_schema = 'public'
909                ORDER BY grantee, table_name, privilege_type
910            "#;
911
912            let rows = sqlx::query(query).fetch_all(&*self.pool).await?;
913            let mut grants = Vec::new();
914
915            for row in rows {
916                let grantee: String = row.get("grantee");
917                let table_name: String = row.get("table_name");
918                let privilege: String = row.get("privilege_type");
919                let is_grantable: String = row.get("is_grantable");
920
921                let privilege_enum = match privilege.as_str() {
922                    "SELECT" => crate::schema::Privilege::Select,
923                    "INSERT" => crate::schema::Privilege::Insert,
924                    "UPDATE" => crate::schema::Privilege::Update,
925                    "DELETE" => crate::schema::Privilege::Delete,
926                    "ALL" => crate::schema::Privilege::All,
927                    _ => crate::schema::Privilege::Select, // Default fallback
928                };
929
930                let grant = crate::schema::Grant::new(
931                    privilege_enum,
932                    crate::schema::GrantTarget::Table {
933                        table: table_name,
934                        schema: None,
935                    },
936                    &grantee,
937                )
938                .with_grant_option(is_grantable == "YES");
939
940                grants.push(grant);
941            }
942
943            Ok(grants)
944        })
945    }
946
947    fn get_schema_version(&self) -> Result<Option<String>> {
948        // PostgreSQL doesn't have a built-in schema version table
949        // Return None for now
950        Ok(None)
951    }
952
953    fn table_exists(&self, table_name: &str) -> Result<bool> {
954        let rt = tokio::runtime::Handle::try_current()
955            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
956
957        rt.block_on(async {
958            let query = r#"
959                SELECT COUNT(*) as count
960                FROM information_schema.tables
961                WHERE table_schema = 'public' 
962                    AND table_name = $1
963            "#;
964
965            let row = sqlx::query(query)
966                .bind(table_name)
967                .fetch_one(&*self.pool)
968                .await?;
969
970            let count: i64 = row.get("count");
971            Ok(count > 0)
972        })
973    }
974
975    fn view_exists(&self, view_name: &str) -> Result<bool> {
976        let rt = tokio::runtime::Handle::try_current()
977            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
978
979        rt.block_on(async {
980            let query = r#"
981                SELECT COUNT(*) as count
982                FROM information_schema.views
983                WHERE table_schema = 'public' 
984                    AND table_name = $1
985            "#;
986
987            let row = sqlx::query(query)
988                .bind(view_name)
989                .fetch_one(&*self.pool)
990                .await?;
991
992            let count: i64 = row.get("count");
993            Ok(count > 0)
994        })
995    }
996
997    fn index_exists(&self, index_name: &str) -> Result<bool> {
998        let rt = tokio::runtime::Handle::try_current()
999            .map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
1000
1001        rt.block_on(async {
1002            let query = r#"
1003                SELECT COUNT(*) as count
1004                FROM pg_indexes
1005                WHERE schemaname = 'public' 
1006                    AND indexname = $1
1007            "#;
1008
1009            let row = sqlx::query(query)
1010                .bind(index_name)
1011                .fetch_one(&*self.pool)
1012                .await?;
1013
1014            let count: i64 = row.get("count");
1015            Ok(count > 0)
1016        })
1017    }
1018}
1019
1020/// PostgreSQL connection manager implementation
1021pub struct PostgreSQLConnectionManager;
1022
1023impl ConnectionManager for PostgreSQLConnectionManager {
1024    fn create_pool(&self, config: &DatabaseConfig) -> Result<Box<dyn ConnectionPool>> {
1025        // For now, create a mock pool to avoid async complexity
1026        // In a real implementation, this would be async or use a different pattern
1027        println!(
1028            "🔧 Creating PostgreSQL connection pool for: {}",
1029            config.database
1030        );
1031
1032        // Create a mock pool - in real implementation this would be an actual PgPool
1033        Ok(Box::new(PostgreSQLConnectionPool {
1034            pool: Arc::new(PgPool::connect_lazy("postgresql://mock").unwrap()),
1035        }))
1036    }
1037
1038    fn test_connection(&self, config: &DatabaseConfig) -> Result<()> {
1039        // For now, just validate the connection string format
1040        let connection_string = self.connection_string(config);
1041        println!("🔍 Testing PostgreSQL connection: {}", connection_string);
1042
1043        // In a real implementation, this would test the actual connection
1044        // For now, we'll just return success
1045        Ok(())
1046    }
1047
1048    fn connection_string(&self, config: &DatabaseConfig) -> String {
1049        format!(
1050            "postgresql://{}:{}@{}:{}/{}",
1051            config.username, config.password, config.host, config.port, config.database
1052        )
1053    }
1054
1055    fn connection_options(&self, config: &DatabaseConfig) -> Result<Box<dyn std::fmt::Debug>> {
1056        let connection_string = self.connection_string(config);
1057        let options = PgConnectOptions::from_str(&connection_string)
1058            .map_err(|e| anyhow::anyhow!("Failed to parse connection string: {}", e))?;
1059        Ok(Box::new(options))
1060    }
1061}
1062
1063/// PostgreSQL connection pool implementation
1064pub struct PostgreSQLConnectionPool {
1065    pool: Arc<PgPool>,
1066}
1067
1068impl ConnectionPool for PostgreSQLConnectionPool {
1069    fn execute_query(
1070        &self,
1071        sql: &str,
1072        params: &[&dyn std::fmt::Display],
1073    ) -> Result<Vec<HashMap<String, String>>> {
1074        // For now, return a simple success response to avoid async complexity
1075        // In a real implementation, this would be async or use a different pattern
1076        println!("🔍 Executing PostgreSQL query: {}", sql);
1077        println!("📊 Parameters: {} items", params.len());
1078
1079        // Return mock data for demonstration
1080        let mut results = Vec::new();
1081        let mut map = HashMap::new();
1082        map.insert("version".to_string(), "PostgreSQL 17.0".to_string());
1083        results.push(map);
1084
1085        Ok(results)
1086    }
1087
1088    fn execute_command(&self, sql: &str, params: &[&dyn std::fmt::Display]) -> Result<u64> {
1089        // For now, return a simple success response to avoid async complexity
1090        println!("🔧 Executing PostgreSQL command: {}", sql);
1091        println!("📊 Parameters: {} items", params.len());
1092
1093        // Return mock affected rows
1094        Ok(1)
1095    }
1096
1097    fn begin_transaction(&self) -> Result<Box<dyn Transaction>> {
1098        let _rt = tokio::runtime::Runtime::new()
1099            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
1100
1101        // TODO: Implement proper transaction handling
1102        Ok(Box::new(PostgreSQLTransaction {}))
1103    }
1104
1105    fn active_connections(&self) -> u32 {
1106        self.pool.size() as u32
1107    }
1108
1109    fn max_connections(&self) -> u32 {
1110        self.pool.options().get_max_connections() as u32
1111    }
1112}
1113
1114/// PostgreSQL transaction implementation
1115pub struct PostgreSQLTransaction {
1116    // Simplified for now - we'll implement proper transaction handling later
1117}
1118
1119impl Transaction for PostgreSQLTransaction {
1120    fn execute_query(
1121        &self,
1122        _sql: &str,
1123        _params: &[&dyn std::fmt::Display],
1124    ) -> Result<Vec<HashMap<String, String>>> {
1125        // TODO: Implement transaction query execution
1126        Err(anyhow::anyhow!(
1127            "Transaction query execution not implemented yet"
1128        ))
1129    }
1130
1131    fn execute_command(&self, _sql: &str, _params: &[&dyn std::fmt::Display]) -> Result<u64> {
1132        // TODO: Implement transaction command execution
1133        Err(anyhow::anyhow!(
1134            "Transaction command execution not implemented yet"
1135        ))
1136    }
1137
1138    fn commit(self: Box<Self>) -> Result<()> {
1139        // TODO: Implement proper transaction commit
1140        Ok(())
1141    }
1142
1143    fn rollback(self: Box<Self>) -> Result<()> {
1144        // TODO: Implement proper transaction rollback
1145        Ok(())
1146    }
1147}
1148
1149/// PostgreSQL migration manager implementation
1150pub struct PostgreSQLMigrationManager {
1151    pool: Arc<sqlx::PgPool>,
1152}
1153
1154impl PostgreSQLMigrationManager {
1155    /// Create a new PostgreSQL migration manager
1156    pub fn new(pool: Arc<sqlx::PgPool>) -> Self {
1157        Self { pool }
1158    }
1159}
1160
1161impl MigrationManager for PostgreSQLMigrationManager {
1162    fn get_applied_migrations(&self) -> Result<Vec<Migration>> {
1163        // Use a blocking runtime to execute the async operation
1164        let rt = tokio::runtime::Runtime::new()
1165            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
1166
1167        rt.block_on(async {
1168            let query = r#"
1169                SELECT name, checksum, applied_at, COALESCE(is_baseline, false) as is_baseline
1170                FROM __ignis_migrations
1171                ORDER BY applied_at ASC
1172            "#;
1173
1174            let rows = sqlx::query(query)
1175                .fetch_all(&*self.pool)
1176                .await
1177                .map_err(|e| anyhow::anyhow!("Failed to fetch migrations: {}", e))?;
1178
1179            let mut migrations = Vec::new();
1180            for row in rows {
1181                let name: String = row.get("name");
1182                let checksum: String = row.get("checksum");
1183
1184                // Convert to our Migration struct
1185                migrations.push(Migration {
1186                    id: name.clone(),
1187                    name,
1188                    up_sql: String::new(), // We don't store the actual SQL in the tracking table
1189                    down_sql: None,
1190                    checksum,
1191                });
1192            }
1193
1194            Ok(migrations)
1195        })
1196    }
1197
1198    fn apply_migration(&self, migration: &Migration) -> Result<()> {
1199        let rt = tokio::runtime::Runtime::new()
1200            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
1201
1202        rt.block_on(async {
1203            // Ensure migration table exists
1204            self.create_migrations_table().await?;
1205
1206            // Execute the migration in a transaction
1207            let mut tx = self
1208                .pool
1209                .begin()
1210                .await
1211                .map_err(|e| anyhow::anyhow!("Failed to begin transaction: {}", e))?;
1212
1213            // Run the migration SQL
1214            sqlx::query(&migration.up_sql)
1215                .execute(&mut *tx)
1216                .await
1217                .map_err(|e| anyhow::anyhow!("Failed to execute migration: {}", e))?;
1218
1219            // Record the migration
1220            let record_sql = r#"
1221                INSERT INTO __ignis_migrations (name, checksum, is_baseline)
1222                VALUES ($1, $2, false)
1223            "#;
1224
1225            sqlx::query(record_sql)
1226                .bind(&migration.name)
1227                .bind(&migration.checksum)
1228                .execute(&mut *tx)
1229                .await
1230                .map_err(|e| anyhow::anyhow!("Failed to record migration: {}", e))?;
1231
1232            tx.commit()
1233                .await
1234                .map_err(|e| anyhow::anyhow!("Failed to commit transaction: {}", e))?;
1235
1236            Ok(())
1237        })
1238    }
1239
1240    fn rollback_migration(&self, migration: &Migration) -> Result<()> {
1241        let rt = tokio::runtime::Runtime::new()
1242            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
1243
1244        rt.block_on(async {
1245            let down_sql = migration.down_sql.as_ref().ok_or_else(|| {
1246                anyhow::anyhow!(
1247                    "No rollback SQL available for migration: {}",
1248                    migration.name
1249                )
1250            })?;
1251
1252            // Execute the rollback in a transaction
1253            let mut tx = self
1254                .pool
1255                .begin()
1256                .await
1257                .map_err(|e| anyhow::anyhow!("Failed to begin transaction: {}", e))?;
1258
1259            // Run the rollback SQL
1260            sqlx::query(down_sql)
1261                .execute(&mut *tx)
1262                .await
1263                .map_err(|e| anyhow::anyhow!("Failed to execute rollback: {}", e))?;
1264
1265            // Remove the migration record
1266            let delete_sql = "DELETE FROM __ignis_migrations WHERE name = $1";
1267            sqlx::query(delete_sql)
1268                .bind(&migration.name)
1269                .execute(&mut *tx)
1270                .await
1271                .map_err(|e| anyhow::anyhow!("Failed to remove migration record: {}", e))?;
1272
1273            tx.commit()
1274                .await
1275                .map_err(|e| anyhow::anyhow!("Failed to commit transaction: {}", e))?;
1276
1277            Ok(())
1278        })
1279    }
1280
1281    fn is_migration_applied(&self, migration_id: &str) -> Result<bool> {
1282        let rt = tokio::runtime::Runtime::new()
1283            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
1284
1285        rt.block_on(async {
1286            let query = "SELECT 1 FROM __ignis_migrations WHERE name = $1";
1287            let result = sqlx::query(query)
1288                .bind(migration_id)
1289                .fetch_optional(&*self.pool)
1290                .await
1291                .map_err(|e| anyhow::anyhow!("Failed to check migration status: {}", e))?;
1292
1293            Ok(result.is_some())
1294        })
1295    }
1296
1297    fn create_migrations_table(&self) -> Result<()> {
1298        let rt = tokio::runtime::Runtime::new()
1299            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
1300
1301        rt.block_on(async { self.create_migrations_table().await })
1302    }
1303
1304    fn get_current_version(&self) -> Result<Option<String>> {
1305        let rt = tokio::runtime::Runtime::new()
1306            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
1307
1308        rt.block_on(async {
1309            let query = "SELECT name FROM __ignis_migrations ORDER BY applied_at DESC LIMIT 1";
1310            let result = sqlx::query(query)
1311                .fetch_optional(&*self.pool)
1312                .await
1313                .map_err(|e| anyhow::anyhow!("Failed to get current version: {}", e))?;
1314
1315            Ok(result.map(|row| row.get::<String, _>("name")))
1316        })
1317    }
1318
1319    fn set_schema_version(&self, _version: &str) -> Result<()> {
1320        // For now, we don't have a separate version table
1321        // This could be implemented as a special migration record
1322        Ok(())
1323    }
1324}
1325
1326impl PostgreSQLMigrationManager {
1327    /// Async version of create_migrations_table for internal use
1328    async fn create_migrations_table(&self) -> Result<()> {
1329        let create_table_sql = r#"
1330            CREATE TABLE IF NOT EXISTS __ignis_migrations (
1331                id SERIAL PRIMARY KEY,
1332                name VARCHAR(255) NOT NULL UNIQUE,
1333                checksum VARCHAR(64) NOT NULL,
1334                applied_at TIMESTAMPTZ DEFAULT NOW(),
1335                is_baseline BOOLEAN DEFAULT false
1336            );
1337        "#;
1338
1339        sqlx::query(create_table_sql)
1340            .execute(&*self.pool)
1341            .await
1342            .map_err(|e| anyhow::anyhow!("Failed to create migrations table: {}", e))?;
1343
1344        Ok(())
1345    }
1346}