use crate::utils::quote_identifier;
use pgrx::prelude::*;
#[pg_extern]
#[allow(clippy::needless_pass_by_value)] fn pg_tviews_convert_table(table_name: String) -> Result<(), Box<dyn std::error::Error>> {
notice!("===== EVENT TRIGGER: pg_tviews_convert_table START for table '{}' =====", table_name);
let Some((schema_name, select_sql)) = crate::hooks::take_pending_tview_select(&table_name)
else {
notice!("DEBUG: No pending SELECT found (likely created by pg_tviews_create, not CTAS)");
return Ok(());
};
notice!("DEBUG: Found cached SELECT ({} chars)", select_sql.len());
notice!("DEBUG: Schema: '{}'", if schema_name.is_empty() { "(empty - will use current_schema())" } else { &schema_name });
let schema_override: Option<&str> = if schema_name.is_empty() {
None
} else {
Some(schema_name.as_str())
};
let drop_sql = match schema_override {
Some(s) => format!(
"DROP TABLE IF EXISTS {}.{} CASCADE",
quote_identifier(s),
quote_identifier(&table_name),
),
None => format!(
"DROP TABLE IF EXISTS {} CASCADE",
quote_identifier(&table_name)
),
};
notice!("DEBUG: Dropping existing table: {}", drop_sql);
Spi::run(&drop_sql).map_err(|e| format!("Failed to drop table '{table_name}': {e}"))?;
notice!("DEBUG: Calling create_tview()...");
match crate::ddl::create_tview(&table_name, &select_sql, schema_override, true) {
Ok(_) => {
notice!("DEBUG: ✅ create_tview() SUCCEEDED for '{}'", table_name);
notice!("DEBUG: ===== EVENT TRIGGER: COMPLETE =====");
Ok(())
}
Err(e) => {
notice!("DEBUG: ❌ create_tview() FAILED for '{}'", table_name);
notice!("DEBUG: Error: {:#?}", e);
notice!("DEBUG: ===== EVENT TRIGGER: FAILED =====");
Err(format!("Failed to create TVIEW '{table_name}': {e}").into())
}
}
}