Skip to main content

dsl_resolve/
scope.rs

1//! The set of bindings visible inside a single statement.
2//!
3//! Looking up `users` after `FROM users u` returns the binding for the
4//! `users` table either by alias `u` or by raw name `users`. The unaliased
5//! form is added so qualified column refs like `users.id` resolve even
6//! when the user never bothered to write an alias.
7
8use crate::binding::Binding;
9use indexmap::IndexMap;
10use serde::Serialize;
11
12#[derive(Debug, Default, Clone, Serialize)]
13pub struct Scope {
14  pub bindings: IndexMap<String, Binding>,
15  /// CTE projection columns, keyed by CTE name. Empty `Vec` means the
16  /// CTE is declared in this statement but the resolver did not (yet)
17  /// inspect its body to learn its columns. Callers should treat
18  /// `Some(empty)` as "exists but unknown" and `None` as "no such CTE".
19  pub cte_columns: IndexMap<String, Vec<String>>,
20}
21
22impl Scope {
23  /// Case-insensitive lookup by alias or bare table name. SQL folds
24  /// unquoted identifiers (PG: lowercase, ANSI: upper), so the user
25  /// typing `U.` must resolve a binding declared as `u`. The fast
26  /// exact-match path runs first; a linear case-insensitive scan
27  /// covers the cold path.
28  pub fn get(&self, name: &str) -> Option<&Binding> {
29    if let Some(b) = self.bindings.get(name) {
30      return Some(b);
31    }
32    self.bindings.iter().find_map(|(k, v)| k.eq_ignore_ascii_case(name).then_some(v))
33  }
34
35  pub fn tables(&self) -> impl Iterator<Item = &Binding> {
36    self.bindings.values()
37  }
38
39  pub fn len(&self) -> usize {
40    self.bindings.len()
41  }
42  pub fn is_empty(&self) -> bool {
43    self.bindings.is_empty()
44  }
45
46  /// CTE columns for `name`, in projection order. Returns `None` when
47  /// the CTE was not declared in this scope; `Some(empty)` when it
48  /// was declared but the resolver could not parse its body yet.
49  /// Matches case-insensitively for the same reason as [`get`].
50  pub fn cte_columns_of(&self, name: &str) -> Option<&Vec<String>> {
51    if let Some(v) = self.cte_columns.get(name) {
52      return Some(v);
53    }
54    self.cte_columns.iter().find_map(|(k, v)| k.eq_ignore_ascii_case(name).then_some(v))
55  }
56}