risingwave_frontend/expr/function_impl/
pg_table_is_visible.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use risingwave_common::id::ObjectId;
16use risingwave_common::session_config::SearchPath;
17use risingwave_expr::{Result, capture_context, function};
18
19use super::context::{AUTH_CONTEXT, CATALOG_READER, DB_NAME, SEARCH_PATH, USER_INFO_READER};
20use crate::catalog::CatalogReader;
21use crate::catalog::system_catalog::is_system_catalog;
22use crate::expr::function_impl::has_privilege::user_not_found_err;
23use crate::session::AuthContext;
24use crate::user::user_service::UserInfoReader;
25
26#[function("pg_table_is_visible(int4) -> boolean")]
27fn pg_table_is_visible(oid: i32) -> Result<Option<bool>> {
28    pg_table_is_visible_impl_captured(ObjectId::new(oid as _))
29}
30
31#[capture_context(CATALOG_READER, USER_INFO_READER, AUTH_CONTEXT, SEARCH_PATH, DB_NAME)]
32fn pg_table_is_visible_impl(
33    catalog: &CatalogReader,
34    user_info: &UserInfoReader,
35    auth_context: &AuthContext,
36    search_path: &SearchPath,
37    db_name: &str,
38    oid: ObjectId,
39) -> Result<Option<bool>> {
40    // To maintain consistency with PostgreSQL, we ensure that system catalogs are always visible.
41    if is_system_catalog(oid) {
42        return Ok(Some(true));
43    }
44
45    let catalog_reader = catalog.read_guard();
46    let user_reader = user_info.read_guard();
47    let user_info = user_reader
48        .get_user_by_name(&auth_context.user_name)
49        .ok_or(user_not_found_err(
50            format!("User {} not found", auth_context.user_name).as_str(),
51        ))?;
52    // Return true only if:
53    // 1. The schema of the object exists in the search path.
54    // 2. User have `USAGE` privilege on the schema.
55    for schema in search_path.path() {
56        if let Ok(schema) = catalog_reader.get_schema_by_name(db_name, schema)
57            && schema.contains_object(oid)
58        {
59            return if user_info.is_super || user_info.has_schema_usage_privilege(schema.id()) {
60                Ok(Some(true))
61            } else {
62                Ok(Some(false))
63            };
64        }
65    }
66
67    Ok(None)
68}