risingwave_frontend/expr/function_impl/
pg_get_viewdef.rsuse std::fmt::Write;
use anyhow::anyhow;
use risingwave_expr::{capture_context, function, ExprError, Result};
use risingwave_sqlparser::ast::Statement;
use risingwave_sqlparser::parser::Parser;
use super::context::{CATALOG_READER, DB_NAME};
use crate::catalog::CatalogReader;
#[function("pg_get_viewdef(int4) -> varchar")]
fn pg_get_viewdef(oid: i32, writer: &mut impl Write) -> Result<()> {
pg_get_viewdef_impl_captured(oid, writer)
}
#[capture_context(CATALOG_READER, DB_NAME)]
fn pg_get_viewdef_impl(
catalog: &CatalogReader,
db_name: &str,
oid: i32,
writer: &mut impl Write,
) -> Result<()> {
let catalog_reader = catalog.read_guard();
if let Ok(view) = catalog_reader.get_view_by_id(db_name, oid as u32) {
write!(writer, "{}", view.sql).unwrap();
Ok(())
} else if let Ok(mv) = catalog_reader.get_created_table_by_id_with_db(db_name, oid as u32) {
let stmts = Parser::parse_sql(&mv.definition).map_err(|e| anyhow!(e))?;
let [stmt]: [_; 1] = stmts.try_into().unwrap();
if let Statement::CreateView {
query,
materialized,
..
} = stmt
&& materialized
{
write!(writer, "{}", query).unwrap();
Ok(())
} else {
Err(ExprError::InvalidParam {
name: "oid",
reason: format!("view or materialized view does not exist: {oid}").into(),
})
}
} else {
Err(ExprError::InvalidParam {
name: "oid",
reason: format!("view or materialized view does not exist: {oid}").into(),
})
}
}