1use std::sync::Arc;
16
17use either::Either;
18use itertools::Itertools;
19use risingwave_common::acl::AclMode;
20use risingwave_common::bail_not_implemented;
21use risingwave_common::catalog::{Field, debug_assert_column_ids_distinct, is_system_schema};
22use risingwave_common::session_config::USER_NAME_WILD_CARD;
23use risingwave_connector::WithPropertiesExt;
24use risingwave_pb::user::grant_privilege::PbObject;
25use risingwave_sqlparser::ast::{AsOf, ObjectName, Statement, TableAlias};
26use risingwave_sqlparser::parser::Parser;
27use thiserror_ext::AsReport;
28
29use super::BoundShare;
30use crate::binder::relation::BoundShareInput;
31use crate::binder::{BindFor, Binder, Relation};
32use crate::catalog::root_catalog::SchemaPath;
33use crate::catalog::source_catalog::SourceCatalog;
34use crate::catalog::system_catalog::SystemTableCatalog;
35use crate::catalog::table_catalog::{TableCatalog, TableType};
36use crate::catalog::view_catalog::ViewCatalog;
37use crate::catalog::{CatalogError, DatabaseId, IndexCatalog, TableId};
38use crate::error::ErrorCode::PermissionDenied;
39use crate::error::{ErrorCode, Result, RwError};
40use crate::handler::privilege::ObjectCheckItem;
41
42#[derive(Debug, Clone)]
43pub struct BoundBaseTable {
44 pub table_id: TableId,
45 pub table_catalog: Arc<TableCatalog>,
46 pub table_indexes: Vec<Arc<IndexCatalog>>,
47 pub as_of: Option<AsOf>,
48}
49
50#[derive(Debug, Clone)]
51pub struct BoundSystemTable {
52 pub table_id: TableId,
53 pub sys_table_catalog: Arc<SystemTableCatalog>,
54}
55
56#[derive(Debug, Clone)]
57pub struct BoundSource {
58 pub catalog: SourceCatalog,
59 pub as_of: Option<AsOf>,
60}
61
62impl BoundSource {
63 pub fn is_shareable_cdc_connector(&self) -> bool {
64 self.catalog.with_properties.is_shareable_cdc_connector()
65 }
66
67 pub fn is_shared(&self) -> bool {
68 self.catalog.info.is_shared()
69 }
70}
71
72impl Binder {
73 pub fn bind_catalog_relation_by_object_name(
74 &mut self,
75 object_name: &ObjectName,
76 bind_creating_relations: bool,
77 ) -> Result<Relation> {
78 let (schema_name, table_name) =
79 Binder::resolve_schema_qualified_name(&self.db_name, object_name)?;
80 self.bind_catalog_relation_by_name(
81 None,
82 schema_name.as_deref(),
83 &table_name,
84 None,
85 None,
86 bind_creating_relations,
87 )
88 }
89
90 pub fn bind_catalog_relation_by_name(
92 &mut self,
93 db_name: Option<&str>,
94 schema_name: Option<&str>,
95 table_name: &str,
96 alias: Option<&TableAlias>,
97 as_of: Option<&AsOf>,
98 bind_creating_relations: bool,
99 ) -> Result<Relation> {
100 let resolve_sys_table_relation = |sys_table_catalog: &Arc<SystemTableCatalog>| {
102 let table = BoundSystemTable {
103 table_id: sys_table_catalog.id(),
104 sys_table_catalog: sys_table_catalog.clone(),
105 };
106 (
107 Relation::SystemTable(Box::new(table)),
108 sys_table_catalog
109 .columns
110 .iter()
111 .map(|c| (c.is_hidden, Field::from(&c.column_desc)))
112 .collect_vec(),
113 )
114 };
115
116 if let Some(db_name) = db_name {
118 let _ = self.catalog.get_database_by_name(db_name)?;
119 }
120
121 let (ret, columns) = {
123 match schema_name {
124 Some(schema_name) => {
125 let db_name = db_name.unwrap_or(&self.db_name).to_owned();
126 let schema_path = SchemaPath::Name(schema_name);
127 if is_system_schema(schema_name) {
128 if let Ok(sys_table_catalog) =
129 self.catalog
130 .get_sys_table_by_name(&db_name, schema_name, table_name)
131 {
132 resolve_sys_table_relation(sys_table_catalog)
133 } else if let Ok((view_catalog, _)) =
134 self.catalog
135 .get_view_by_name(&db_name, schema_path, table_name)
136 {
137 self.resolve_view_relation(&view_catalog.clone())?
138 } else {
139 bail_not_implemented!(
140 issue = 1695,
141 r###"{}.{} is not supported, please use `SHOW` commands for now.
142`SHOW TABLES`,
143`SHOW MATERIALIZED VIEWS`,
144`DESCRIBE <table>`,
145`SHOW COLUMNS FROM [table]`
146"###,
147 schema_name,
148 table_name
149 );
150 }
151 } else if let Some(source_catalog) =
152 self.temporary_source_manager.get_source(table_name)
153 {
155 self.resolve_source_relation(&source_catalog.clone(), as_of, true)?
156 } else if let Ok((table_catalog, schema_name)) = self
157 .catalog
158 .get_any_table_by_name(&db_name, schema_path, table_name)
159 && (bind_creating_relations
160 || table_catalog.is_internal_table()
161 || table_catalog.is_created())
162 {
163 self.resolve_table_relation(
164 table_catalog.clone(),
165 &db_name,
166 schema_name,
167 as_of,
168 )?
169 } else if let Ok((source_catalog, _)) =
170 self.catalog
171 .get_source_by_name(&db_name, schema_path, table_name)
172 {
173 self.resolve_source_relation(&source_catalog.clone(), as_of, false)?
174 } else if let Ok((view_catalog, _)) =
175 self.catalog
176 .get_view_by_name(&db_name, schema_path, table_name)
177 {
178 self.resolve_view_relation(&view_catalog.clone())?
179 } else if let Some(table_catalog) =
180 self.staging_catalog_manager.get_table(table_name)
181 {
182 self.resolve_table_relation(
184 table_catalog.clone().into(),
185 &db_name,
186 schema_name,
187 as_of,
188 )?
189 } else {
190 return Err(CatalogError::NotFound(
191 "table or source",
192 table_name.to_owned(),
193 )
194 .into());
195 }
196 }
197 None => (|| {
198 assert!(db_name.is_none());
201 let db_name = self.db_name.clone();
202 let user_name = self.auth_context.user_name.clone();
203
204 for path in self.search_path.path() {
205 if is_system_schema(path)
206 && let Ok(sys_table_catalog) = self
207 .catalog
208 .get_sys_table_by_name(&db_name, path, table_name)
209 {
210 return Ok(resolve_sys_table_relation(sys_table_catalog));
211 } else {
212 let schema_name = if path == USER_NAME_WILD_CARD {
213 &user_name
214 } else {
215 &path.clone()
216 };
217
218 if let Ok(schema) =
219 self.catalog.get_schema_by_name(&db_name, schema_name)
220 {
221 if let Some(source_catalog) =
222 self.temporary_source_manager.get_source(table_name)
223 {
225 return self.resolve_source_relation(
226 &source_catalog.clone(),
227 as_of,
228 true,
229 );
230 } else if let Some(table_catalog) =
231 schema.get_any_table_by_name(table_name)
232 && (bind_creating_relations
233 || table_catalog.is_internal_table()
234 || table_catalog.is_created())
235 {
236 return self.resolve_table_relation(
237 table_catalog.clone(),
238 &db_name,
239 schema_name,
240 as_of,
241 );
242 } else if let Some(source_catalog) =
243 schema.get_source_by_name(table_name)
244 {
245 return self.resolve_source_relation(
246 &source_catalog.clone(),
247 as_of,
248 false,
249 );
250 } else if let Some(view_catalog) =
251 schema.get_view_by_name(table_name)
252 {
253 return self.resolve_view_relation(&view_catalog.clone());
254 } else if let Some(table_catalog) =
255 self.staging_catalog_manager.get_table(table_name)
256 {
257 return self.resolve_table_relation(
259 table_catalog.clone().into(),
260 &db_name,
261 schema_name,
262 as_of,
263 );
264 }
265 }
266 }
267 }
268
269 Err(CatalogError::NotFound("table or source", table_name.to_owned()).into())
270 })()?,
271 }
272 };
273
274 self.bind_table_to_context(columns, table_name.to_owned(), alias)?;
275 Ok(ret)
276 }
277
278 pub(crate) fn check_privilege(
279 &self,
280 item: ObjectCheckItem,
281 database_id: DatabaseId,
282 ) -> Result<()> {
283 if self.context.disable_security_invoker {
285 return Ok(());
286 }
287
288 match self.bind_for {
289 BindFor::Stream | BindFor::Batch => {
290 if matches!(self.bind_for, BindFor::Stream)
292 && self.database_id != database_id
293 && matches!(item.object, PbObject::SourceId(_))
294 {
295 return Err(PermissionDenied(format!(
296 "SOURCE \"{}\" is not allowed for cross-db access",
297 item.name
298 ))
299 .into());
300 }
301 if let Some(user) = self.user.get_user_by_name(&self.auth_context.user_name) {
302 if user.is_super || user.id == item.owner {
303 return Ok(());
304 }
305 if !user.has_privilege(item.object, item.mode) {
306 return Err(PermissionDenied(item.error_message()).into());
307 }
308
309 if self.database_id != database_id
311 && !user.has_privilege(database_id, AclMode::Connect)
312 {
313 let db_name = self.catalog.get_database_by_id(database_id)?.name.clone();
314
315 return Err(PermissionDenied(format!(
316 "permission denied for database \"{db_name}\""
317 ))
318 .into());
319 }
320 } else {
321 return Err(PermissionDenied("Session user is invalid".to_owned()).into());
322 }
323 }
324 BindFor::Ddl | BindFor::System => {
325 }
327 }
328 Ok(())
329 }
330
331 fn resolve_table_relation(
332 &mut self,
333 table_catalog: Arc<TableCatalog>,
334 db_name: &str,
335 schema_name: &str,
336 as_of: Option<&AsOf>,
337 ) -> Result<(Relation, Vec<(bool, Field)>)> {
338 let table_id = table_catalog.id();
339 let columns = table_catalog
340 .columns
341 .iter()
342 .map(|c| (c.is_hidden, Field::from(&c.column_desc)))
343 .collect_vec();
344 self.check_privilege(
345 ObjectCheckItem::new(
346 table_catalog.owner,
347 AclMode::Select,
348 table_catalog.name.clone(),
349 table_id,
350 ),
351 table_catalog.database_id,
352 )?;
353 self.included_relations.insert(table_id.as_object_id());
354
355 let table_indexes = self.resolve_table_indexes(db_name, schema_name, table_id)?;
356
357 let table = BoundBaseTable {
358 table_id,
359 table_catalog,
360 table_indexes,
361 as_of: as_of.cloned(),
362 };
363
364 Ok::<_, RwError>((Relation::BaseTable(Box::new(table)), columns))
365 }
366
367 fn resolve_source_relation(
368 &mut self,
369 source_catalog: &SourceCatalog,
370 as_of: Option<&AsOf>,
371 is_temporary: bool,
372 ) -> Result<(Relation, Vec<(bool, Field)>)> {
373 debug_assert_column_ids_distinct(&source_catalog.columns);
374 if !is_temporary {
375 self.check_privilege(
376 ObjectCheckItem::new(
377 source_catalog.owner,
378 AclMode::Select,
379 source_catalog.name.clone(),
380 source_catalog.id,
381 ),
382 source_catalog.database_id,
383 )?;
384 }
385 self.included_relations
386 .insert(source_catalog.id.as_object_id());
387 Ok((
388 Relation::Source(Box::new(BoundSource {
389 catalog: source_catalog.clone(),
390 as_of: as_of.cloned(),
391 })),
392 source_catalog
393 .columns
394 .iter()
395 .map(|c| (c.is_hidden, Field::from(&c.column_desc)))
396 .collect_vec(),
397 ))
398 }
399
400 fn resolve_view_relation(
401 &mut self,
402 view_catalog: &ViewCatalog,
403 ) -> Result<(Relation, Vec<(bool, Field)>)> {
404 if !view_catalog.is_system_view() {
405 self.check_privilege(
406 ObjectCheckItem::new(
407 view_catalog.owner,
408 AclMode::Select,
409 view_catalog.name.clone(),
410 view_catalog.id,
411 ),
412 view_catalog.database_id,
413 )?;
414 }
415
416 let ast = Parser::parse_sql(&view_catalog.sql)
417 .expect("a view's sql should be parsed successfully");
418 let Statement::Query(query) = ast
419 .into_iter()
420 .exactly_one()
421 .expect("a view should contain only one statement")
422 else {
423 unreachable!("a view should contain a query statement");
424 };
425 let query = self.bind_query_for_view(&query).map_err(|e| {
426 ErrorCode::BindError(format!(
427 "failed to bind view {}, sql: {}\nerror: {}",
428 view_catalog.name,
429 view_catalog.sql,
430 e.as_report()
431 ))
432 })?;
433
434 let columns = view_catalog.columns.clone();
435
436 if !itertools::equal(
437 query.schema().fields().iter().map(|f| &f.data_type),
438 view_catalog.columns.iter().map(|f| &f.data_type),
439 ) {
440 return Err(ErrorCode::BindError(format!(
441 "failed to bind view {}. The SQL's schema is different from catalog's schema sql: {}, bound schema: {:?}, catalog schema: {:?}",
442 view_catalog.name, view_catalog.sql, query.schema(), columns
443 )).into());
444 }
445
446 let share_id = match self.shared_views.get(&view_catalog.id) {
447 Some(share_id) => *share_id,
448 None => {
449 let share_id = self.next_share_id();
450 self.shared_views.insert(view_catalog.id, share_id);
451 self.included_relations
452 .insert(view_catalog.id.as_object_id());
453 share_id
454 }
455 };
456 let input = Either::Left(query);
457 Ok((
458 Relation::Share(Box::new(BoundShare {
459 share_id,
460 input: BoundShareInput::Query(input),
461 })),
462 columns.iter().map(|c| (false, c.clone())).collect_vec(),
463 ))
464 }
465
466 fn resolve_table_indexes(
467 &self,
468 db_name: &str,
469 schema_name: &str,
470 table_id: TableId,
471 ) -> Result<Vec<Arc<IndexCatalog>>> {
472 let schema = self.catalog.get_schema_by_name(db_name, schema_name)?;
473 assert!(
474 schema.get_table_by_id(table_id).is_some() || table_id.is_placeholder(),
475 "table {table_id} not found in {db_name}.{schema_name}"
476 );
477
478 Ok(schema.get_created_indexes_by_table_id(table_id))
479 }
480
481 pub(crate) fn bind_table(
482 &mut self,
483 schema_name: Option<&str>,
484 table_name: &str,
485 ) -> Result<BoundBaseTable> {
486 let db_name = &self.db_name;
487 let schema_path = self.bind_schema_path(schema_name);
488 let (table_catalog, schema_name) =
489 self.catalog
490 .get_created_table_by_name(db_name, schema_path, table_name)?;
491 let table_catalog = table_catalog.clone();
492
493 let table_id = table_catalog.id();
494 let table_indexes = self.resolve_table_indexes(db_name, schema_name, table_id)?;
495
496 let columns = table_catalog.columns.clone();
497
498 self.bind_table_to_context(
499 columns
500 .iter()
501 .map(|c| (c.is_hidden, (&c.column_desc).into())),
502 table_name.to_owned(),
503 None,
504 )?;
505
506 Ok(BoundBaseTable {
507 table_id,
508 table_catalog,
509 table_indexes,
510 as_of: None,
511 })
512 }
513
514 pub(crate) fn check_for_dml(table: &TableCatalog, is_insert: bool) -> Result<()> {
515 let table_name = &table.name;
516 match table.table_type() {
517 TableType::Table => {}
518 TableType::Index | TableType::VectorIndex => {
519 return Err(ErrorCode::InvalidInputSyntax(format!(
520 "cannot change index \"{table_name}\""
521 ))
522 .into());
523 }
524 TableType::MaterializedView => {
525 return Err(ErrorCode::InvalidInputSyntax(format!(
526 "cannot change materialized view \"{table_name}\""
527 ))
528 .into());
529 }
530 TableType::Internal => {
531 return Err(ErrorCode::InvalidInputSyntax(format!(
532 "cannot change internal table \"{table_name}\""
533 ))
534 .into());
535 }
536 }
537
538 if table.append_only && !is_insert {
539 return Err(ErrorCode::BindError(
540 "append-only table does not support update or delete".to_owned(),
541 )
542 .into());
543 }
544
545 Ok(())
546 }
547}