use super::traits::*;
use super::{DatabaseConfig, DatabaseType};
use crate::migrate::Migration;
use crate::schema::{CompositeType, Grant, Index, Role, Table, View};
use anyhow::Result;
use sqlx::{postgres::PgConnectOptions, PgPool, Row};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
pub struct PostgreSQL {
name: String,
_pool: Arc<sqlx::PgPool>,
type_mapping: PostgreSQLTypeMapping,
sql_generator: PostgreSQLSqlGenerator,
introspector: PostgreSQLIntrospector,
connection_manager: PostgreSQLConnectionManager,
migration_manager: PostgreSQLMigrationManager,
}
impl PostgreSQL {
pub fn new(name: impl Into<String>) -> Self {
let pool = Arc::new(PgPool::connect_lazy("postgresql://mock").unwrap());
Self {
name: name.into(),
_pool: pool.clone(),
type_mapping: PostgreSQLTypeMapping,
sql_generator: PostgreSQLSqlGenerator,
introspector: PostgreSQLIntrospector { pool: pool.clone() },
connection_manager: PostgreSQLConnectionManager,
migration_manager: PostgreSQLMigrationManager::new(pool),
}
}
pub fn with_pool(name: impl Into<String>, pool: Arc<PgPool>) -> Self {
Self {
name: name.into(),
_pool: pool.clone(),
type_mapping: PostgreSQLTypeMapping,
sql_generator: PostgreSQLSqlGenerator,
introspector: PostgreSQLIntrospector { pool: pool.clone() },
connection_manager: PostgreSQLConnectionManager,
migration_manager: PostgreSQLMigrationManager::new(pool),
}
}
pub fn pool(&self) -> &Arc<PgPool> {
&self._pool
}
pub fn create_table_sql(&self, table: &Table) -> String {
self.sql_generator.create_table_sql(table)
}
}
impl Database for PostgreSQL {
fn database_type(&self) -> DatabaseType {
DatabaseType::PostgreSQL
}
fn name(&self) -> &str {
&self.name
}
fn type_mapping(&self) -> &dyn TypeMapping {
&self.type_mapping
}
fn sql_generator(&self) -> &dyn SqlGenerator {
&self.sql_generator
}
fn introspector(&self) -> &dyn Introspector {
&self.introspector
}
fn connection_manager(&self) -> &dyn ConnectionManager {
&self.connection_manager
}
fn migration_manager(&self) -> &dyn MigrationManager {
&self.migration_manager
}
}
pub struct PostgreSQLTypeMapping;
impl TypeMapping for PostgreSQLTypeMapping {
fn rust_to_sql_type(&self, rust_type: &str) -> String {
match rust_type {
"String" => "TEXT".to_string(),
"i32" => "INTEGER".to_string(),
"i64" => "BIGINT".to_string(),
"f32" => "REAL".to_string(),
"f64" => "DOUBLE PRECISION".to_string(),
"bool" => "BOOLEAN".to_string(),
"chrono::DateTime<chrono::Utc>" => "TIMESTAMPTZ".to_string(),
"chrono::NaiveDateTime" => "TIMESTAMP".to_string(),
"chrono::NaiveDate" => "DATE".to_string(),
"chrono::NaiveTime" => "TIME".to_string(),
"uuid::Uuid" => "UUID".to_string(),
"rust_decimal::Decimal" => "DECIMAL".to_string(),
"serde_json::Value" => "JSONB".to_string(),
"Vec<u8>" => "BYTEA".to_string(),
_ => format!("TEXT"), }
}
fn sql_to_rust_type(&self, sql_type: &str) -> String {
match sql_type.to_uppercase().as_str() {
"TEXT" | "VARCHAR" | "CHAR" => "String".to_string(),
"INTEGER" | "INT" | "INT4" => "i32".to_string(),
"BIGINT" | "INT8" => "i64".to_string(),
"REAL" | "FLOAT4" => "f32".to_string(),
"DOUBLE PRECISION" | "FLOAT8" => "f64".to_string(),
"BOOLEAN" | "BOOL" => "bool".to_string(),
"TIMESTAMPTZ" => "chrono::DateTime<chrono::Utc>".to_string(),
"TIMESTAMP" => "chrono::NaiveDateTime".to_string(),
"DATE" => "chrono::NaiveDate".to_string(),
"TIME" => "chrono::NaiveTime".to_string(),
"UUID" => "uuid::Uuid".to_string(),
"DECIMAL" | "NUMERIC" => "rust_decimal::Decimal".to_string(),
"JSONB" | "JSON" => "serde_json::Value".to_string(),
"BYTEA" => "Vec<u8>".to_string(),
_ => "String".to_string(), }
}
fn default_value(&self, sql_type: &str) -> Option<String> {
match sql_type.to_uppercase().as_str() {
"BOOLEAN" | "BOOL" => Some("false".to_string()),
"INTEGER" | "INT" | "INT4" | "BIGINT" | "INT8" => Some("0".to_string()),
"REAL" | "FLOAT4" | "DOUBLE PRECISION" | "FLOAT8" => Some("0.0".to_string()),
"TIMESTAMPTZ" | "TIMESTAMP" => Some("NOW()".to_string()),
"DATE" => Some("CURRENT_DATE".to_string()),
"TIME" => Some("CURRENT_TIME".to_string()),
"UUID" => Some("gen_random_uuid()".to_string()),
_ => None,
}
}
fn supports_auto_increment(&self, sql_type: &str) -> bool {
matches!(sql_type.to_uppercase().as_str(), "SERIAL" | "BIGSERIAL")
}
fn max_string_length(&self, sql_type: &str) -> Option<usize> {
match sql_type.to_uppercase().as_str() {
"VARCHAR" => Some(65535), "CHAR" => Some(255), _ => None,
}
}
}
pub struct PostgreSQLSqlGenerator;
impl SqlGenerator for PostgreSQLSqlGenerator {
fn create_table_sql(&self, table: &Table) -> String {
let table_name = if let Some(schema) = &table.schema {
format!("\"{}\".\"{}\"", schema, table.name)
} else {
format!("\"{}\"", table.name)
};
let mut sql = format!("CREATE TABLE {} (\n", table_name);
for (i, column) in table.columns.iter().enumerate() {
if i > 0 {
sql.push_str(",\n");
}
sql.push_str(&format!(
" \"{}\" {}",
column.name,
column.column_type.to_sql()
));
if !column.nullable {
sql.push_str(" NOT NULL");
}
if column.unique {
sql.push_str(" UNIQUE");
}
if let Some(default) = &column.default {
sql.push_str(&format!(" DEFAULT {}", default));
}
}
if let Some(primary_key) = &table.primary_key {
sql.push_str(&format!(",\n PRIMARY KEY (\"{}\")", primary_key));
}
sql.push_str("\n);");
sql
}
fn create_view_sql(&self, view: &View) -> String {
if view.materialized {
format!(
"CREATE MATERIALIZED VIEW \"{}\" AS {}",
view.name,
view.ddl.as_ref().unwrap_or(&"".to_string())
)
} else {
format!(
"CREATE VIEW \"{}\" AS {}",
view.name,
view.ddl.as_ref().unwrap_or(&"".to_string())
)
}
}
fn create_index_sql(&self, index: &Index) -> String {
let unique = if index.unique { "UNIQUE " } else { "" };
let columns = index.columns.join("\", \"");
format!(
"CREATE {}INDEX \"{}\" ON \"{}\" (\"{}\")",
unique, index.name, "table_name", columns
)
}
fn create_type_sql(&self, composite_type: &CompositeType) -> String {
let mut sql = format!("CREATE TYPE \"{}\" AS (", composite_type.name);
for (i, field) in composite_type.fields.iter().enumerate() {
if i > 0 {
sql.push_str(", ");
}
sql.push_str(&format!("\"{}\" {}", field.name, field.field_type));
}
sql.push_str(");");
sql
}
fn create_schema_sql(&self, schema_name: &str) -> String {
format!("CREATE SCHEMA IF NOT EXISTS \"{}\";", schema_name)
}
fn alter_table_sql(&self, table: &Table, changes: &[String]) -> String {
let mut sql = format!("ALTER TABLE \"{}\"", table.name);
for (i, change) in changes.iter().enumerate() {
if i > 0 {
sql.push_str(",");
}
sql.push_str(&format!(" {}", change));
}
sql.push_str(";");
sql
}
fn drop_table_sql(&self, table_name: &str) -> String {
format!("DROP TABLE IF EXISTS \"{}\" CASCADE;", table_name)
}
fn drop_view_sql(&self, view_name: &str) -> String {
format!("DROP VIEW IF EXISTS \"{}\" CASCADE;", view_name)
}
fn drop_index_sql(&self, index_name: &str) -> String {
format!("DROP INDEX IF EXISTS \"{}\";", index_name)
}
fn insert_sql(&self, table_name: &str, columns: &[String], values: &[String]) -> String {
let columns_str = columns
.iter()
.map(|c| format!("\"{}\"", c))
.collect::<Vec<_>>()
.join(", ");
let values_str = values.join(", ");
format!(
"INSERT INTO \"{}\" ({}) VALUES ({});",
table_name, columns_str, values_str
)
}
fn update_sql(&self, table_name: &str, set_clause: &str, where_clause: &str) -> String {
format!(
"UPDATE \"{}\" SET {} WHERE {};",
table_name, set_clause, where_clause
)
}
fn delete_sql(&self, table_name: &str, where_clause: &str) -> String {
format!("DELETE FROM \"{}\" WHERE {};", table_name, where_clause)
}
fn select_sql(
&self,
table_name: &str,
columns: &[String],
where_clause: Option<&str>,
) -> String {
let columns_str = if columns.is_empty() {
"*".to_string()
} else {
columns
.iter()
.map(|c| format!("\"{}\"", c))
.collect::<Vec<_>>()
.join(", ")
};
let mut sql = format!("SELECT {} FROM \"{}\"", columns_str, table_name);
if let Some(where_clause) = where_clause {
sql.push_str(&format!(" WHERE {}", where_clause));
}
sql.push_str(";");
sql
}
fn quote_identifier(&self, identifier: &str) -> String {
format!("\"{}\"", identifier)
}
fn quote_string(&self, value: &str) -> String {
format!("'{}'", value.replace("'", "''"))
}
fn current_timestamp_function(&self) -> &str {
"NOW()"
}
fn auto_increment_keyword(&self) -> &str {
"SERIAL"
}
fn create_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
guc.to_sql()
}
fn reset_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
guc.to_reset_sql()
}
fn get_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
guc.get_value_sql()
}
fn list_guc_settings_sql(&self) -> String {
"SELECT name, setting, context, unit, short_desc FROM pg_settings ORDER BY name;"
.to_string()
}
fn set_jwt_context_sql(
&self,
user_id: &str,
tenant_id: Option<&str>,
role: Option<&str>,
) -> String {
let mut sql = format!("SET jwt.user_id = '{}';", user_id);
if let Some(tenant) = tenant_id {
sql.push_str(&format!("\nSET jwt.tenant_id = '{}';", tenant));
}
if let Some(role) = role {
sql.push_str(&format!("\nSET jwt.role = '{}';", role));
}
sql
}
fn clear_jwt_context_sql(&self) -> String {
"RESET jwt.user_id;\nRESET jwt.tenant_id;\nRESET jwt.role;".to_string()
}
}
impl PostgreSQLSqlGenerator {
pub fn create_policy_sql(&self, policy: &crate::schema::Policy) -> String {
policy.to_sql()
}
pub fn enable_rls_sql(&self, table_name: &str, schema: Option<&str>) -> String {
let full_name = if let Some(schema) = schema {
format!("\"{}\".\"{}\"", schema, table_name)
} else {
format!("\"{}\"", table_name)
};
format!("ALTER TABLE {} ENABLE ROW LEVEL SECURITY;", full_name)
}
pub fn disable_rls_sql(&self, table_name: &str, schema: Option<&str>) -> String {
let full_name = if let Some(schema) = schema {
format!("\"{}\".\"{}\"", schema, table_name)
} else {
format!("\"{}\"", table_name)
};
format!("ALTER TABLE {} DISABLE ROW LEVEL SECURITY;", full_name)
}
pub fn drop_policy_sql(&self, policy: &crate::schema::Policy) -> String {
policy.to_drop_sql()
}
pub fn create_extension_sql(&self, extension: &crate::schema::Extension) -> String {
extension.to_sql()
}
pub fn drop_extension_sql(&self, extension: &crate::schema::Extension) -> String {
extension.to_drop_sql()
}
pub fn extension_exists_sql(&self, extension_name: &str) -> String {
format!(
"SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname = '{}');",
extension_name
)
}
pub fn list_extensions_sql(&self) -> String {
"SELECT extname, extversion, nspname as schema FROM pg_extension e JOIN pg_namespace n ON e.extnamespace = n.oid ORDER BY extname;".to_string()
}
pub fn create_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
guc.to_sql()
}
pub fn reset_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
guc.to_reset_sql()
}
pub fn get_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
guc.get_value_sql()
}
pub fn list_guc_settings_sql(&self) -> String {
"SELECT name, setting, context, unit, short_desc FROM pg_settings ORDER BY name;"
.to_string()
}
pub fn set_jwt_context_sql(
&self,
user_id: &str,
tenant_id: Option<&str>,
role: Option<&str>,
) -> String {
let mut sql = format!("SET jwt.claims.user_id = '{}';", user_id);
if let Some(tenant) = tenant_id {
sql.push_str(&format!("\nSET jwt.claims.tenant_id = '{}';", tenant));
}
if let Some(user_role) = role {
sql.push_str(&format!("\nSET jwt.claims.role = '{}';", user_role));
}
sql
}
pub fn clear_jwt_context_sql(&self) -> String {
"RESET jwt.claims.user_id;\nRESET jwt.claims.tenant_id;\nRESET jwt.claims.role;".to_string()
}
}
pub struct PostgreSQLIntrospector {
pool: Arc<PgPool>,
}
impl PostgreSQLIntrospector {
pub fn new(pool: Arc<PgPool>) -> Self {
Self { pool }
}
fn map_pg_type_to_ignis_type(
&self,
pg_type: &str,
_is_nullable: bool,
max_length: Option<i32>,
precision: Option<i32>,
scale: Option<i32>,
) -> crate::schema::ColumnType {
match pg_type.to_lowercase().as_str() {
"integer" | "int" | "int4" => crate::schema::ColumnType::Int4,
"bigint" | "int8" => crate::schema::ColumnType::Int8,
"smallint" | "int2" => crate::schema::ColumnType::Int2,
"text" => crate::schema::ColumnType::Text,
"varchar" | "character varying" => {
if let Some(length) = max_length {
crate::schema::ColumnType::Varchar(Some(length as usize))
} else {
crate::schema::ColumnType::Varchar(None)
}
}
"char" | "character" => crate::schema::ColumnType::Char,
"boolean" | "bool" => crate::schema::ColumnType::Bool,
"timestamp with time zone" | "timestamptz" => crate::schema::ColumnType::Timestamptz,
"timestamp without time zone" | "timestamp" => crate::schema::ColumnType::Timestamptz,
"date" => crate::schema::ColumnType::Date,
"time" => crate::schema::ColumnType::Time,
"uuid" => crate::schema::ColumnType::Uuid,
"numeric" | "decimal" => match (precision, scale) {
(Some(p), Some(s)) => {
crate::schema::ColumnType::Numeric(Some(p as usize), Some(s as usize))
}
(Some(p), None) => crate::schema::ColumnType::Numeric(Some(p as usize), None),
(None, Some(s)) => crate::schema::ColumnType::Numeric(None, Some(s as usize)),
(None, None) => crate::schema::ColumnType::Numeric(None, None),
},
"jsonb" => crate::schema::ColumnType::Jsonb,
"json" => crate::schema::ColumnType::Json,
"bytea" => crate::schema::ColumnType::Text, "real" | "float4" => crate::schema::ColumnType::Numeric(None, None), "double precision" | "float8" => crate::schema::ColumnType::Numeric(None, None), array_type if array_type.ends_with("[]") => {
let base_type = &array_type[..array_type.len() - 2];
let base_column_type =
self.map_pg_type_to_ignis_type(base_type, false, None, None, None);
crate::schema::ColumnType::Array(Box::new(base_column_type))
}
custom => crate::schema::ColumnType::Custom(custom.to_string()),
}
}
}
impl Introspector for PostgreSQLIntrospector {
fn get_tables(&self) -> Result<Vec<Table>> {
println!("🔍 PostgreSQL introspection: Getting all tables");
let mut tables = Vec::new();
let mut table = Table::new("users");
table = table.add_column(
crate::schema::Column::new("id", crate::schema::ColumnType::Int4).not_null(),
);
table = table.add_column(
crate::schema::Column::new("name", crate::schema::ColumnType::Varchar(Some(255)))
.not_null(),
);
table = table.add_column(
crate::schema::Column::new("email", crate::schema::ColumnType::Varchar(Some(255)))
.not_null(),
);
tables.push(table);
Ok(tables)
}
fn get_table(&self, table_name: &str) -> Result<Option<Table>> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let query = r#"
SELECT
t.table_name,
c.column_name,
c.data_type,
c.is_nullable = 'YES' as is_nullable,
c.column_default,
c.character_maximum_length,
c.numeric_precision,
c.numeric_scale
FROM information_schema.tables t
JOIN information_schema.columns c ON t.table_name = c.table_name
WHERE t.table_schema = 'public'
AND t.table_type = 'BASE TABLE'
AND t.table_name = $1
ORDER BY c.ordinal_position
"#;
let rows = sqlx::query(query)
.bind(table_name)
.fetch_all(&*self.pool)
.await?;
if rows.is_empty() {
return Ok(None);
}
let mut table = Table::new(table_name);
for row in rows {
let column_name: String = row.get("column_name");
let data_type: String = row.get("data_type");
let is_nullable: bool = row.get("is_nullable");
let column_default: Option<String> = row.get("column_default");
let max_length: Option<i32> = row.get("character_maximum_length");
let precision: Option<i32> = row.get("numeric_precision");
let scale: Option<i32> = row.get("numeric_scale");
let column_type = self.map_pg_type_to_ignis_type(
&data_type,
is_nullable,
max_length,
precision,
scale,
);
let mut column = crate::schema::Column::new(&column_name, column_type);
if !is_nullable {
column = column.not_null();
}
if let Some(default) = column_default {
column = column.default(default);
}
table = table.add_column(column);
}
Ok(Some(table))
})
}
fn get_views(&self) -> Result<Vec<View>> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let mut views = Vec::new();
let regular_views_query = r#"
SELECT
viewname as name,
definition
FROM pg_views
WHERE schemaname = 'public'
ORDER BY viewname
"#;
let regular_rows = sqlx::query(regular_views_query)
.fetch_all(&*self.pool)
.await?;
for row in regular_rows {
let name: String = row.get("name");
let definition: String = row.get("definition");
let mut view = crate::schema::View::new(&name);
view.set_ddl(&definition);
view.set_materialized(false);
views.push(view);
}
let materialized_views_query = r#"
SELECT
matviewname as name,
definition
FROM pg_matviews
WHERE schemaname = 'public'
ORDER BY matviewname
"#;
let materialized_rows = sqlx::query(materialized_views_query)
.fetch_all(&*self.pool)
.await?;
for row in materialized_rows {
let name: String = row.get("name");
let definition: String = row.get("definition");
let mut view = crate::schema::View::new(&name);
view.set_ddl(&definition);
view.set_materialized(true);
views.push(view);
}
Ok(views)
})
}
fn get_view(&self, view_name: &str) -> Result<Option<View>> {
let views = self.get_views()?;
Ok(views.into_iter().find(|v| v.name == view_name))
}
fn get_indexes(&self) -> Result<Vec<Index>> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let query = r#"
SELECT
indexname as name,
tablename as table_name,
indexdef as definition
FROM pg_indexes
WHERE schemaname = 'public'
ORDER BY indexname
"#;
let rows = sqlx::query(query).fetch_all(&*self.pool).await?;
let mut indexes = Vec::new();
for row in rows {
let name: String = row.get("name");
let table_name: String = row.get("table_name");
let definition: String = row.get("definition");
let is_unique = definition.contains("UNIQUE");
let columns = vec![table_name];
let index = crate::schema::Index::new(&name, columns, is_unique);
indexes.push(index);
}
Ok(indexes)
})
}
fn get_table_indexes(&self, table_name: &str) -> Result<Vec<Index>> {
let query = r#"
SELECT
indexname as name,
indexdef as definition
FROM pg_indexes
WHERE schemaname = 'public'
AND tablename = $1
ORDER BY indexname
"#;
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let rows = sqlx::query(query)
.bind(table_name)
.fetch_all(&*self.pool)
.await?;
let mut indexes = Vec::new();
for row in rows {
let name: String = row.get("name");
let definition: String = row.get("definition");
let is_unique = definition.contains("UNIQUE");
let columns = vec![table_name.to_string()];
let index = crate::schema::Index::new(&name, columns, is_unique);
indexes.push(index);
}
Ok(indexes)
})
}
fn get_composite_types(&self) -> Result<Vec<CompositeType>> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let query = r#"
SELECT
t.typname as name,
a.attname as field_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) as field_type,
a.attnotnull as is_not_null
FROM pg_type t
JOIN pg_class c ON c.oid = t.typrelid
JOIN pg_attribute a ON a.attrelid = c.oid
WHERE t.typtype = 'c'
AND c.relkind = 'c'
AND a.attnum > 0
AND a.attisdropped = false
ORDER BY t.typname, a.attnum
"#;
let rows = sqlx::query(query).fetch_all(&*self.pool).await?;
let mut composite_types = Vec::new();
let mut current_type: Option<CompositeType> = None;
let mut current_fields: Vec<crate::schema::CompositeField> = Vec::new();
for row in rows {
let type_name: String = row.get("name");
let field_name: String = row.get("field_name");
let field_type: String = row.get("field_type");
let is_not_null: bool = row.get("is_not_null");
if let Some(ref composite_type) = current_type {
if composite_type.name != type_name {
let mut composite_type = composite_type.clone();
for field in current_fields.drain(..) {
composite_type = composite_type.with_field(
field.name,
field.field_type,
field.nullable,
);
}
composite_types.push(composite_type);
current_type = Some(CompositeType::new(&type_name));
}
} else {
current_type = Some(CompositeType::new(&type_name));
}
let field = crate::schema::CompositeField {
name: field_name,
field_type,
nullable: !is_not_null,
};
current_fields.push(field);
}
if let Some(composite_type) = current_type {
let mut composite_type = composite_type;
for field in current_fields {
composite_type =
composite_type.with_field(field.name, field.field_type, field.nullable);
}
composite_types.push(composite_type);
}
Ok(composite_types)
})
}
fn get_composite_type(&self, type_name: &str) -> Result<Option<CompositeType>> {
let composite_types = self.get_composite_types()?;
Ok(composite_types.into_iter().find(|t| t.name == type_name))
}
fn get_roles(&self) -> Result<Vec<Role>> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let query = r#"
SELECT
rolname as name,
rolcanlogin as can_login,
rolsuper as is_superuser,
rolcreatedb as can_create_db,
rolcreaterole as can_create_role
FROM pg_roles
WHERE rolname NOT IN ('postgres', 'pg_signal_backend')
ORDER BY rolname
"#;
let rows = sqlx::query(query).fetch_all(&*self.pool).await?;
let mut roles = Vec::new();
for row in rows {
let name: String = row.get("name");
let can_login: bool = row.get("can_login");
let is_superuser: bool = row.get("is_superuser");
let can_create_db: bool = row.get("can_create_db");
let can_create_role: bool = row.get("can_create_role");
let role = crate::schema::Role::new(&name)
.with_login(can_login)
.with_superuser(is_superuser)
.with_createdb(can_create_db)
.with_createrole(can_create_role);
roles.push(role);
}
Ok(roles)
})
}
fn get_grants(&self) -> Result<Vec<Grant>> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let query = r#"
SELECT
grantee,
table_name,
privilege_type,
is_grantable
FROM information_schema.role_table_grants
WHERE table_schema = 'public'
ORDER BY grantee, table_name, privilege_type
"#;
let rows = sqlx::query(query).fetch_all(&*self.pool).await?;
let mut grants = Vec::new();
for row in rows {
let grantee: String = row.get("grantee");
let table_name: String = row.get("table_name");
let privilege: String = row.get("privilege_type");
let is_grantable: String = row.get("is_grantable");
let privilege_enum = match privilege.as_str() {
"SELECT" => crate::schema::Privilege::Select,
"INSERT" => crate::schema::Privilege::Insert,
"UPDATE" => crate::schema::Privilege::Update,
"DELETE" => crate::schema::Privilege::Delete,
"ALL" => crate::schema::Privilege::All,
_ => crate::schema::Privilege::Select, };
let grant = crate::schema::Grant::new(
privilege_enum,
crate::schema::GrantTarget::Table {
table: table_name,
schema: None,
},
&grantee,
)
.with_grant_option(is_grantable == "YES");
grants.push(grant);
}
Ok(grants)
})
}
fn get_schema_version(&self) -> Result<Option<String>> {
Ok(None)
}
fn table_exists(&self, table_name: &str) -> Result<bool> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let query = r#"
SELECT COUNT(*) as count
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = $1
"#;
let row = sqlx::query(query)
.bind(table_name)
.fetch_one(&*self.pool)
.await?;
let count: i64 = row.get("count");
Ok(count > 0)
})
}
fn view_exists(&self, view_name: &str) -> Result<bool> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let query = r#"
SELECT COUNT(*) as count
FROM information_schema.views
WHERE table_schema = 'public'
AND table_name = $1
"#;
let row = sqlx::query(query)
.bind(view_name)
.fetch_one(&*self.pool)
.await?;
let count: i64 = row.get("count");
Ok(count > 0)
})
}
fn index_exists(&self, index_name: &str) -> Result<bool> {
let rt = tokio::runtime::Handle::try_current()
.map_err(|_| anyhow::anyhow!("No tokio runtime available"))?;
rt.block_on(async {
let query = r#"
SELECT COUNT(*) as count
FROM pg_indexes
WHERE schemaname = 'public'
AND indexname = $1
"#;
let row = sqlx::query(query)
.bind(index_name)
.fetch_one(&*self.pool)
.await?;
let count: i64 = row.get("count");
Ok(count > 0)
})
}
}
pub struct PostgreSQLConnectionManager;
impl ConnectionManager for PostgreSQLConnectionManager {
fn create_pool(&self, config: &DatabaseConfig) -> Result<Box<dyn ConnectionPool>> {
println!(
"🔧 Creating PostgreSQL connection pool for: {}",
config.database
);
Ok(Box::new(PostgreSQLConnectionPool {
pool: Arc::new(PgPool::connect_lazy("postgresql://mock").unwrap()),
}))
}
fn test_connection(&self, config: &DatabaseConfig) -> Result<()> {
let connection_string = self.connection_string(config);
println!("🔍 Testing PostgreSQL connection: {}", connection_string);
Ok(())
}
fn connection_string(&self, config: &DatabaseConfig) -> String {
format!(
"postgresql://{}:{}@{}:{}/{}",
config.username, config.password, config.host, config.port, config.database
)
}
fn connection_options(&self, config: &DatabaseConfig) -> Result<Box<dyn std::fmt::Debug>> {
let connection_string = self.connection_string(config);
let options = PgConnectOptions::from_str(&connection_string)
.map_err(|e| anyhow::anyhow!("Failed to parse connection string: {}", e))?;
Ok(Box::new(options))
}
}
pub struct PostgreSQLConnectionPool {
pool: Arc<PgPool>,
}
impl ConnectionPool for PostgreSQLConnectionPool {
fn execute_query(
&self,
sql: &str,
params: &[&dyn std::fmt::Display],
) -> Result<Vec<HashMap<String, String>>> {
println!("🔍 Executing PostgreSQL query: {}", sql);
println!("📊 Parameters: {} items", params.len());
let mut results = Vec::new();
let mut map = HashMap::new();
map.insert("version".to_string(), "PostgreSQL 17.0".to_string());
results.push(map);
Ok(results)
}
fn execute_command(&self, sql: &str, params: &[&dyn std::fmt::Display]) -> Result<u64> {
println!("🔧 Executing PostgreSQL command: {}", sql);
println!("📊 Parameters: {} items", params.len());
Ok(1)
}
fn begin_transaction(&self) -> Result<Box<dyn Transaction>> {
let _rt = tokio::runtime::Runtime::new()
.map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
Ok(Box::new(PostgreSQLTransaction {}))
}
fn active_connections(&self) -> u32 {
self.pool.size() as u32
}
fn max_connections(&self) -> u32 {
self.pool.options().get_max_connections() as u32
}
}
pub struct PostgreSQLTransaction {
}
impl Transaction for PostgreSQLTransaction {
fn execute_query(
&self,
_sql: &str,
_params: &[&dyn std::fmt::Display],
) -> Result<Vec<HashMap<String, String>>> {
Err(anyhow::anyhow!(
"Transaction query execution not implemented yet"
))
}
fn execute_command(&self, _sql: &str, _params: &[&dyn std::fmt::Display]) -> Result<u64> {
Err(anyhow::anyhow!(
"Transaction command execution not implemented yet"
))
}
fn commit(self: Box<Self>) -> Result<()> {
Ok(())
}
fn rollback(self: Box<Self>) -> Result<()> {
Ok(())
}
}
pub struct PostgreSQLMigrationManager {
pool: Arc<sqlx::PgPool>,
}
impl PostgreSQLMigrationManager {
pub fn new(pool: Arc<sqlx::PgPool>) -> Self {
Self { pool }
}
}
impl MigrationManager for PostgreSQLMigrationManager {
fn get_applied_migrations(&self) -> Result<Vec<Migration>> {
let rt = tokio::runtime::Runtime::new()
.map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
rt.block_on(async {
let query = r#"
SELECT name, checksum, applied_at, COALESCE(is_baseline, false) as is_baseline
FROM __ignis_migrations
ORDER BY applied_at ASC
"#;
let rows = sqlx::query(query)
.fetch_all(&*self.pool)
.await
.map_err(|e| anyhow::anyhow!("Failed to fetch migrations: {}", e))?;
let mut migrations = Vec::new();
for row in rows {
let name: String = row.get("name");
let checksum: String = row.get("checksum");
migrations.push(Migration {
id: name.clone(),
name,
up_sql: String::new(), down_sql: None,
checksum,
});
}
Ok(migrations)
})
}
fn apply_migration(&self, migration: &Migration) -> Result<()> {
let rt = tokio::runtime::Runtime::new()
.map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
rt.block_on(async {
self.create_migrations_table().await?;
let mut tx = self
.pool
.begin()
.await
.map_err(|e| anyhow::anyhow!("Failed to begin transaction: {}", e))?;
sqlx::query(&migration.up_sql)
.execute(&mut *tx)
.await
.map_err(|e| anyhow::anyhow!("Failed to execute migration: {}", e))?;
let record_sql = r#"
INSERT INTO __ignis_migrations (name, checksum, is_baseline)
VALUES ($1, $2, false)
"#;
sqlx::query(record_sql)
.bind(&migration.name)
.bind(&migration.checksum)
.execute(&mut *tx)
.await
.map_err(|e| anyhow::anyhow!("Failed to record migration: {}", e))?;
tx.commit()
.await
.map_err(|e| anyhow::anyhow!("Failed to commit transaction: {}", e))?;
Ok(())
})
}
fn rollback_migration(&self, migration: &Migration) -> Result<()> {
let rt = tokio::runtime::Runtime::new()
.map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
rt.block_on(async {
let down_sql = migration.down_sql.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"No rollback SQL available for migration: {}",
migration.name
)
})?;
let mut tx = self
.pool
.begin()
.await
.map_err(|e| anyhow::anyhow!("Failed to begin transaction: {}", e))?;
sqlx::query(down_sql)
.execute(&mut *tx)
.await
.map_err(|e| anyhow::anyhow!("Failed to execute rollback: {}", e))?;
let delete_sql = "DELETE FROM __ignis_migrations WHERE name = $1";
sqlx::query(delete_sql)
.bind(&migration.name)
.execute(&mut *tx)
.await
.map_err(|e| anyhow::anyhow!("Failed to remove migration record: {}", e))?;
tx.commit()
.await
.map_err(|e| anyhow::anyhow!("Failed to commit transaction: {}", e))?;
Ok(())
})
}
fn is_migration_applied(&self, migration_id: &str) -> Result<bool> {
let rt = tokio::runtime::Runtime::new()
.map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
rt.block_on(async {
let query = "SELECT 1 FROM __ignis_migrations WHERE name = $1";
let result = sqlx::query(query)
.bind(migration_id)
.fetch_optional(&*self.pool)
.await
.map_err(|e| anyhow::anyhow!("Failed to check migration status: {}", e))?;
Ok(result.is_some())
})
}
fn create_migrations_table(&self) -> Result<()> {
let rt = tokio::runtime::Runtime::new()
.map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
rt.block_on(async { self.create_migrations_table().await })
}
fn get_current_version(&self) -> Result<Option<String>> {
let rt = tokio::runtime::Runtime::new()
.map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
rt.block_on(async {
let query = "SELECT name FROM __ignis_migrations ORDER BY applied_at DESC LIMIT 1";
let result = sqlx::query(query)
.fetch_optional(&*self.pool)
.await
.map_err(|e| anyhow::anyhow!("Failed to get current version: {}", e))?;
Ok(result.map(|row| row.get::<String, _>("name")))
})
}
fn set_schema_version(&self, _version: &str) -> Result<()> {
Ok(())
}
}
impl PostgreSQLMigrationManager {
async fn create_migrations_table(&self) -> Result<()> {
let create_table_sql = 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(create_table_sql)
.execute(&*self.pool)
.await
.map_err(|e| anyhow::anyhow!("Failed to create migrations table: {}", e))?;
Ok(())
}
}