1use std::cell::RefCell;
16use std::collections::hash_map::Entry;
17use std::collections::{BTreeMap, HashMap, HashSet};
18use std::rc::Rc;
19
20use parse_display::Display;
21use risingwave_common::catalog::Field;
22use risingwave_common::types::DataType;
23use risingwave_sqlparser::ast::{TableAlias, WindowSpec};
24
25use crate::binder::Relation;
26use crate::error::{ErrorCode, Result};
27use crate::expr::{ExprImpl, ScopeId};
28
29type LiteResult<T> = std::result::Result<T, ErrorCode>;
30
31use crate::binder::{BoundQuery, COLUMN_GROUP_PREFIX, ShareId};
32
33#[derive(Debug, Clone)]
34pub struct ColumnBinding {
35 pub table_name: String,
36 pub schema_name: Option<String>,
37 pub table_alias: Option<String>,
39 pub index: usize,
40 pub is_hidden: bool,
41 pub field: Field,
42}
43
44impl ColumnBinding {
45 pub fn new(
46 table_name: String,
47 schema_name: Option<String>,
48 table_alias: Option<String>,
49 index: usize,
50 is_hidden: bool,
51 field: Field,
52 ) -> Self {
53 ColumnBinding {
54 table_name,
55 schema_name,
56 table_alias,
57 index,
58 is_hidden,
59 field,
60 }
61 }
62}
63
64#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Display)]
65#[display(style = "TITLE CASE")]
66pub enum Clause {
67 Where,
68 Values,
69 GroupBy,
70 JoinOn,
71 Having,
72 Filter,
73 From,
74 GeneratedColumn,
75 Insert,
76}
77
78pub struct LateralBindContext {
81 pub is_visible: bool,
82 pub context: BindContext,
83}
84
85#[derive(Debug, Clone)]
86pub enum BindingCteState {
87 Bound { query: BoundQuery },
89
90 ChangeLog {
91 table: Relation,
92 key_indices: Option<Vec<usize>>,
93 distribution_key_indices: Option<Vec<usize>>,
94 },
95}
96
97#[derive(Clone, Debug)]
98pub struct BindingCte {
99 pub share_id: ShareId,
100 pub state: BindingCteState,
101 pub alias: TableAlias,
102}
103
104#[derive(Default, Debug, Clone)]
105pub struct BindContext {
106 pub columns: Vec<ColumnBinding>,
108 pub indices_of: HashMap<String, Vec<usize>>,
110 pub range_of: HashMap<(Option<String>, String), (usize, usize)>,
112 pub clause: Option<Clause>,
114 pub column_group_context: ColumnGroupContext,
116 pub cte_to_relation: HashMap<String, Rc<RefCell<BindingCte>>>,
119 pub cte_relation_names: HashSet<String>,
121 pub lambda_args: Option<HashMap<String, (usize, DataType)>>,
123 pub disable_security_invoker: bool,
125 pub named_windows: HashMap<String, WindowSpec>,
127 pub sql_udf_arguments: Option<HashMap<String, ExprImpl>>,
130 pub scope: ScopeId,
132}
133
134#[derive(Default, Debug, Clone)]
136pub struct ColumnGroupContext {
137 pub mapping: HashMap<usize, u32>,
139 pub groups: BTreeMap<u32, ColumnGroup>,
142
143 next_group_id: u32,
144}
145
146#[derive(Default, Debug, Clone)]
149pub struct ColumnGroup {
150 pub indices: HashSet<usize>,
152 pub non_nullable_column: Option<usize>,
156
157 pub column_name: Option<String>,
158}
159
160impl BindContext {
161 pub fn get_column_binding_index(
162 &self,
163 schema_name: &Option<String>,
164 table_name: &Option<String>,
165 column_name: &String,
166 ) -> LiteResult<usize> {
167 match &self.get_column_binding_indices(schema_name, table_name, column_name)?[..] {
168 [] => unreachable!(),
169 [idx] => Ok(*idx),
170 _ => Err(ErrorCode::InvalidReference(format!(
171 "column reference \"{}\" is ambiguous",
172 column_name
173 ))),
174 }
175 }
176
177 pub fn get_column_binding_indices(
181 &self,
182 schema_name: &Option<String>,
183 table_name: &Option<String>,
184 column_name: &String,
185 ) -> LiteResult<Vec<usize>> {
186 match table_name {
187 Some(table_name) => {
188 if let Some(group_id_str) = table_name.strip_prefix(COLUMN_GROUP_PREFIX) {
189 let group_id = group_id_str.parse::<u32>().map_err(|_|ErrorCode::InternalError(
190 format!("Could not parse {:?} as virtual table name `{COLUMN_GROUP_PREFIX}[group_id]`", table_name)))?;
191 self.get_indices_with_group_id(group_id, column_name)
192 } else {
193 Ok(vec![self.get_index_with_table_name(
194 column_name,
195 table_name,
196 schema_name,
197 )?])
198 }
199 }
200 None => self.get_unqualified_indices(column_name),
201 }
202 }
203
204 pub fn get_table_alias(
205 &self,
206 schema_name: &String,
207 table_name: &String,
208 column_name: &String,
209 ) -> LiteResult<Option<usize>> {
210 let column_indexes = self
211 .indices_of
212 .get(column_name)
213 .ok_or_else(|| ErrorCode::ItemNotFound(format!("Invalid column: {}", column_name)))?;
214 for index in column_indexes {
215 let column = &self.columns[*index];
216 if let (Some(schema), Some(table_alias)) = (&column.schema_name, &column.table_alias)
217 && schema == schema_name
218 && table_alias == table_name
219 {
220 return Ok(Some(*index));
221 }
222 }
223 Ok(None)
224 }
225
226 fn get_indices_with_group_id(
227 &self,
228 group_id: u32,
229 column_name: &String,
230 ) -> LiteResult<Vec<usize>> {
231 let Some(group) = self
234 .column_group_context
235 .groups
236 .get(&group_id)
237 .filter(|group| {
238 group
239 .column_name
240 .as_ref()
241 .is_none_or(|name| name == column_name)
242 })
243 else {
244 return Err(ErrorCode::ItemNotFound(format!(
245 "Invalid column: {column_name}"
246 )));
247 };
248 if let Some(non_nullable) = &group.non_nullable_column {
249 Ok(vec![*non_nullable])
250 } else {
251 let mut indices: Vec<_> = group.indices.iter().copied().collect();
253 indices.sort(); Ok(indices)
255 }
256 }
257
258 pub fn get_unqualified_indices(&self, column_name: &String) -> LiteResult<Vec<usize>> {
259 let columns = self
260 .indices_of
261 .get(column_name)
262 .ok_or_else(|| ErrorCode::ItemNotFound(format!("Invalid column: {column_name}")))?;
263 if columns.len() > 1 {
264 if let Some(group_id) = self.column_group_context.mapping.get(&columns[0]) {
267 let group = self.column_group_context.groups.get(group_id).unwrap();
268 if columns.iter().all(|idx| group.indices.contains(idx)) {
269 if let Some(non_nullable) = &group.non_nullable_column {
270 return Ok(vec![*non_nullable]);
271 } else {
272 return Ok(columns.clone());
274 }
275 }
276 }
277 Err(ErrorCode::InvalidReference(format!(
278 "column reference \"{}\" is ambiguous",
279 column_name
280 )))
281 } else {
282 Ok(columns.clone())
283 }
284 }
285
286 pub fn check_catalog_name(&self, exposed_relation_name: &str) -> Result<()> {
287 if self.cte_relation_names.contains(exposed_relation_name) {
288 return Err(ErrorCode::DuplicateRelationName(format!(
289 "table name \"{}\" specified more than once",
290 exposed_relation_name
291 ))
292 .into());
293 }
294 Ok(())
295 }
296
297 pub fn add_cte_name(&mut self, exposed_relation_name: String) {
298 self.cte_relation_names.insert(exposed_relation_name);
299 }
300
301 fn has_relation_name(&self, relation_name: &str) -> bool {
302 self.range_of
303 .keys()
304 .any(|(_, existing_name)| existing_name == relation_name)
305 }
306
307 pub fn check_relation_name_conflict(&self, relation_name: &str) -> Result<()> {
308 if self.has_relation_name(relation_name) {
309 return Err(ErrorCode::DuplicateRelationName(format!(
310 "table name \"{}\" specified more than once",
311 relation_name
312 ))
313 .into());
314 }
315 Ok(())
316 }
317
318 fn check_cte_relation_name_conflict(&self, other: &Self) -> Result<()> {
319 for cte_relation_name in &self.cte_relation_names {
322 other.check_relation_name_conflict(cte_relation_name)?;
323 }
324 for cte_relation_name in &other.cte_relation_names {
327 self.check_relation_name_conflict(cte_relation_name)?;
328 }
329 Ok(())
330 }
331
332 pub fn add_natural_columns(
335 &mut self,
336 left: usize,
337 right: usize,
338 non_nullable_column: Option<usize>,
339 ) {
340 match (
341 self.column_group_context.mapping.get(&left).copied(),
342 self.column_group_context.mapping.get(&right).copied(),
343 ) {
344 (None, None) => {
345 let group_id = self.column_group_context.next_group_id;
346 self.column_group_context.next_group_id += 1;
347
348 let group = ColumnGroup {
349 indices: HashSet::from([left, right]),
350 non_nullable_column,
351 column_name: Some(self.columns[left].field.name.clone()),
352 };
353 self.column_group_context.groups.insert(group_id, group);
354 self.column_group_context.mapping.insert(left, group_id);
355 self.column_group_context.mapping.insert(right, group_id);
356 }
357 (Some(group_id), None) => {
358 let group = self.column_group_context.groups.get_mut(&group_id).unwrap();
359 group.indices.insert(right);
360 if group.non_nullable_column.is_none() {
361 group.non_nullable_column = non_nullable_column;
362 }
363 self.column_group_context.mapping.insert(right, group_id);
364 }
365 (None, Some(group_id)) => {
366 let group = self.column_group_context.groups.get_mut(&group_id).unwrap();
367 group.indices.insert(left);
368 if group.non_nullable_column.is_none() {
369 group.non_nullable_column = non_nullable_column;
370 }
371 self.column_group_context.mapping.insert(left, group_id);
372 }
373 (Some(l_group_id), Some(r_group_id)) => {
374 if r_group_id == l_group_id {
375 return;
376 }
377
378 let r_group = self
379 .column_group_context
380 .groups
381 .remove(&r_group_id)
382 .unwrap();
383 let l_group = self
384 .column_group_context
385 .groups
386 .get_mut(&l_group_id)
387 .unwrap();
388
389 for idx in &r_group.indices {
390 *self.column_group_context.mapping.get_mut(idx).unwrap() = l_group_id;
391 l_group.indices.insert(*idx);
392 }
393 if l_group.non_nullable_column.is_none() {
394 l_group.non_nullable_column = if r_group.non_nullable_column.is_none() {
395 non_nullable_column
396 } else {
397 r_group.non_nullable_column
398 };
399 }
400 }
401 }
402 }
403
404 fn get_index_with_table_name(
411 &self,
412 column_name: &String,
413 table_name: &String,
414 schema_name: &Option<String>,
415 ) -> LiteResult<usize> {
416 let chosen_range = self.resolve_relation_range(table_name, schema_name)?;
417 self.resolve_column_in_range(column_name, table_name, chosen_range)
418 }
419
420 pub(super) fn resolve_relation_range(
424 &self,
425 table_name: &String,
426 schema_name: &Option<String>,
427 ) -> LiteResult<(usize, usize)> {
428 let mut alias_ranges = Vec::new();
429 let mut base_ranges = Vec::new();
430
431 for ((rel_schema, rel_name), range) in &self.range_of {
432 if rel_name != table_name
433 || !schema_name
434 .as_deref()
435 .is_none_or(|s| rel_schema.as_deref() == Some(s))
436 {
437 continue;
438 }
439
440 let is_alias = if range.0 == range.1 {
443 rel_schema.is_none()
444 } else {
445 self.columns[range.0].table_alias.is_some()
446 };
447 if is_alias {
448 alias_ranges.push(*range);
449 } else {
450 base_ranges.push(*range);
451 }
452 }
453
454 let chosen_ranges = if alias_ranges.is_empty() {
455 base_ranges
456 } else {
457 alias_ranges
458 };
459
460 match chosen_ranges.as_slice() {
461 [] => Err(ErrorCode::ItemNotFound(format!(
462 "missing FROM-clause entry for table \"{}\"",
463 table_name
464 ))),
465 [range] => Ok(*range),
466 _ => Err(ErrorCode::InvalidReference(format!(
467 "table reference \"{}\" is ambiguous",
468 table_name
469 ))),
470 }
471 }
472
473 fn resolve_column_in_range(
475 &self,
476 column_name: &String,
477 table_name: &String,
478 range: (usize, usize),
479 ) -> LiteResult<usize> {
480 let idxs = self
481 .indices_of
482 .get(column_name)
483 .ok_or_else(|| ErrorCode::ItemNotFound(format!("Invalid column: {}", column_name)))?;
484
485 let matched: Vec<_> = idxs
486 .iter()
487 .copied()
488 .filter(|index| (range.0..range.1).contains(index))
489 .collect();
490
491 match matched.as_slice() {
492 [] => Err(ErrorCode::ItemNotFound(format!(
493 "missing FROM-clause entry for table \"{}\"",
494 table_name
495 ))),
496 [column_index] => Ok(*column_index),
497 _ => Err(ErrorCode::InvalidReference(format!(
498 "column reference \"{}\" is ambiguous",
499 column_name
500 ))),
501 }
502 }
503
504 pub fn merge_context(&mut self, other: Self) -> Result<()> {
507 self.check_cte_relation_name_conflict(&other)?;
508
509 let begin = self.columns.len();
510 self.columns.extend(other.columns.into_iter().map(|mut c| {
511 c.index += begin;
512 c
513 }));
514 for (k, v) in other.indices_of {
515 let entry = self.indices_of.entry(k).or_default();
516 entry.extend(v.into_iter().map(|x| x + begin));
517 }
518 for (k, (x, y)) in other.range_of {
519 match self.range_of.entry(k) {
520 Entry::Occupied(e) => {
521 return Err(ErrorCode::InternalError(format!(
522 "Duplicated table name while merging adjacent contexts: {}",
523 e.key().1
524 ))
525 .into());
526 }
527 Entry::Vacant(entry) => {
528 entry.insert((begin + x, begin + y));
529 }
530 }
531 }
532 self.cte_relation_names.extend(other.cte_relation_names);
533 let ColumnGroupContext {
536 mapping,
537 groups,
538 next_group_id,
539 } = other.column_group_context;
540
541 let offset = self.column_group_context.next_group_id;
542 for (idx, group_id) in mapping {
543 self.column_group_context
544 .mapping
545 .insert(begin + idx, offset + group_id);
546 }
547 for (group_id, mut group) in groups {
548 group.indices = group.indices.into_iter().map(|idx| idx + begin).collect();
549 if let Some(col) = &mut group.non_nullable_column {
550 *col += begin;
551 }
552 self.column_group_context
553 .groups
554 .insert(offset + group_id, group);
555 }
556 self.column_group_context.next_group_id += next_group_id;
557
558 Ok(())
560 }
561}
562
563impl BindContext {
564 pub fn new() -> Self {
565 Self::default()
566 }
567}