risingwave_frontend/expr/function_impl/
pg_get_viewdef.rs1use anyhow::anyhow;
16use risingwave_expr::{ExprError, Result, capture_context, function};
17use risingwave_sqlparser::ast::Statement;
18
19use super::context::{CATALOG_READER, DB_NAME};
20use crate::catalog::CatalogReader;
21
22#[function("pg_get_viewdef(int4) -> varchar")]
23fn pg_get_viewdef(oid: i32, writer: &mut impl std::fmt::Write) -> Result<()> {
24 pg_get_viewdef_pretty(oid, false, writer)
25}
26
27#[function("pg_get_viewdef(int4, boolean) -> varchar")]
28fn pg_get_viewdef_pretty(oid: i32, _pretty: bool, writer: &mut impl std::fmt::Write) -> Result<()> {
29 pg_get_viewdef_impl_captured(oid, writer)
30}
31
32#[capture_context(CATALOG_READER, DB_NAME)]
33fn pg_get_viewdef_impl(
34 catalog: &CatalogReader,
35 db_name: &str,
36 oid: i32,
37 writer: &mut impl std::fmt::Write,
38) -> Result<()> {
39 let catalog_reader = catalog.read_guard();
40
41 if let Ok(view) = catalog_reader.get_view_by_id(db_name, oid as u32) {
42 write!(writer, "{}", view.sql).unwrap();
43 Ok(())
44 } else if let Ok(mv) = catalog_reader.get_created_table_by_id_with_db(db_name, oid as u32) {
45 let stmt = mv.create_sql_ast().map_err(|e| anyhow!(e))?;
46 if let Statement::CreateView {
47 query,
48 materialized,
49 ..
50 } = stmt
51 && materialized
52 {
53 write!(writer, "{}", query).unwrap();
54 Ok(())
55 } else {
56 Err(ExprError::InvalidParam {
57 name: "oid",
58 reason: format!("view or materialized view does not exist: {oid}").into(),
59 })
60 }
61 } else {
62 Err(ExprError::InvalidParam {
63 name: "oid",
64 reason: format!("view or materialized view does not exist: {oid}").into(),
65 })
66 }
67}