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