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(&PbObject::DatabaseId(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 PbObject::TableId(table_id.table_id),
350 ),
351 table_catalog.database_id,
352 )?;
353 self.included_relations.insert(table_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 PbObject::SourceId(source_catalog.id),
381 ),
382 source_catalog.database_id,
383 )?;
384 }
385 self.included_relations.insert(source_catalog.id.into());
386 Ok((
387 Relation::Source(Box::new(BoundSource {
388 catalog: source_catalog.clone(),
389 as_of: as_of.cloned(),
390 })),
391 source_catalog
392 .columns
393 .iter()
394 .map(|c| (c.is_hidden, Field::from(&c.column_desc)))
395 .collect_vec(),
396 ))
397 }
398
399 fn resolve_view_relation(
400 &mut self,
401 view_catalog: &ViewCatalog,
402 ) -> Result<(Relation, Vec<(bool, Field)>)> {
403 if !view_catalog.is_system_view() {
404 self.check_privilege(
405 ObjectCheckItem::new(
406 view_catalog.owner,
407 AclMode::Select,
408 view_catalog.name.clone(),
409 PbObject::ViewId(view_catalog.id),
410 ),
411 view_catalog.database_id,
412 )?;
413 }
414
415 let ast = Parser::parse_sql(&view_catalog.sql)
416 .expect("a view's sql should be parsed successfully");
417 let Statement::Query(query) = ast
418 .into_iter()
419 .exactly_one()
420 .expect("a view should contain only one statement")
421 else {
422 unreachable!("a view should contain a query statement");
423 };
424 let query = self.bind_query_for_view(&query).map_err(|e| {
425 ErrorCode::BindError(format!(
426 "failed to bind view {}, sql: {}\nerror: {}",
427 view_catalog.name,
428 view_catalog.sql,
429 e.as_report()
430 ))
431 })?;
432
433 let columns = view_catalog.columns.clone();
434
435 if !itertools::equal(
436 query.schema().fields().iter().map(|f| &f.data_type),
437 view_catalog.columns.iter().map(|f| &f.data_type),
438 ) {
439 return Err(ErrorCode::BindError(format!(
440 "failed to bind view {}. The SQL's schema is different from catalog's schema sql: {}, bound schema: {:?}, catalog schema: {:?}",
441 view_catalog.name, view_catalog.sql, query.schema(), columns
442 )).into());
443 }
444
445 let share_id = match self.shared_views.get(&view_catalog.id) {
446 Some(share_id) => *share_id,
447 None => {
448 let share_id = self.next_share_id();
449 self.shared_views.insert(view_catalog.id, share_id);
450 self.included_relations.insert(view_catalog.id.into());
451 share_id
452 }
453 };
454 let input = Either::Left(query);
455 Ok((
456 Relation::Share(Box::new(BoundShare {
457 share_id,
458 input: BoundShareInput::Query(input),
459 })),
460 columns.iter().map(|c| (false, c.clone())).collect_vec(),
461 ))
462 }
463
464 fn resolve_table_indexes(
465 &self,
466 db_name: &str,
467 schema_name: &str,
468 table_id: TableId,
469 ) -> Result<Vec<Arc<IndexCatalog>>> {
470 let schema = self.catalog.get_schema_by_name(db_name, schema_name)?;
471 assert!(
472 schema.get_table_by_id(&table_id).is_some() || table_id.is_placeholder(),
473 "table {table_id} not found in {db_name}.{schema_name}"
474 );
475
476 Ok(schema.get_created_indexes_by_table_id(&table_id))
477 }
478
479 pub(crate) fn bind_table(
480 &mut self,
481 schema_name: Option<&str>,
482 table_name: &str,
483 ) -> Result<BoundBaseTable> {
484 let db_name = &self.db_name;
485 let schema_path = self.bind_schema_path(schema_name);
486 let (table_catalog, schema_name) =
487 self.catalog
488 .get_created_table_by_name(db_name, schema_path, table_name)?;
489 let table_catalog = table_catalog.clone();
490
491 let table_id = table_catalog.id();
492 let table_indexes = self.resolve_table_indexes(db_name, schema_name, table_id)?;
493
494 let columns = table_catalog.columns.clone();
495
496 self.bind_table_to_context(
497 columns
498 .iter()
499 .map(|c| (c.is_hidden, (&c.column_desc).into())),
500 table_name.to_owned(),
501 None,
502 )?;
503
504 Ok(BoundBaseTable {
505 table_id,
506 table_catalog,
507 table_indexes,
508 as_of: None,
509 })
510 }
511
512 pub(crate) fn check_for_dml(table: &TableCatalog, is_insert: bool) -> Result<()> {
513 let table_name = &table.name;
514 match table.table_type() {
515 TableType::Table => {}
516 TableType::Index | TableType::VectorIndex => {
517 return Err(ErrorCode::InvalidInputSyntax(format!(
518 "cannot change index \"{table_name}\""
519 ))
520 .into());
521 }
522 TableType::MaterializedView => {
523 return Err(ErrorCode::InvalidInputSyntax(format!(
524 "cannot change materialized view \"{table_name}\""
525 ))
526 .into());
527 }
528 TableType::Internal => {
529 return Err(ErrorCode::InvalidInputSyntax(format!(
530 "cannot change internal table \"{table_name}\""
531 ))
532 .into());
533 }
534 }
535
536 if table.append_only && !is_insert {
537 return Err(ErrorCode::BindError(
538 "append-only table does not support update or delete".to_owned(),
539 )
540 .into());
541 }
542
543 Ok(())
544 }
545}