toasty_core/stmt/
table_ref.rs

1use crate::stmt::{ExprArg, TableDerived};
2
3use super::TableId;
4
5/// A reference to a table within a [`SourceTable`](super::SourceTable).
6///
7/// Each entry in [`SourceTable::tables`](super::SourceTable) is a `TableRef`
8/// that identifies where data comes from: a schema table, a CTE, a derived
9/// subquery, or a placeholder argument.
10///
11/// # Examples
12///
13/// ```ignore
14/// use toasty_core::stmt::TableRef;
15/// use toasty_core::schema::db::TableId;
16///
17/// let table_ref = TableRef::Table(TableId(0));
18/// assert!(table_ref.references(TableId(0)));
19/// assert!(!table_ref.is_cte());
20/// ```
21#[derive(Debug, Clone, PartialEq)]
22pub enum TableRef {
23    /// A reference to a CTE defined in a `WITH` clause.
24    Cte {
25        /// How many nesting levels up the CTE is defined relative to this
26        /// reference.
27        nesting: usize,
28
29        /// The index of the CTE within the [`With::ctes`](super::With) vector.
30        index: usize,
31    },
32
33    /// A derived table (inline subquery).
34    Derived(TableDerived),
35
36    /// A schema-defined table.
37    Table(TableId),
38
39    /// A placeholder that will be replaced with a derived table at a later
40    /// compilation stage.
41    Arg(ExprArg),
42}
43
44impl TableRef {
45    /// Returns `true` if this ref points to the given schema table.
46    pub fn references(&self, table_id: TableId) -> bool {
47        match self {
48            Self::Cte { .. } => false,
49            Self::Derived { .. } => false,
50            Self::Table(id) => id == &table_id,
51            Self::Arg { .. } => todo!(),
52        }
53    }
54
55    /// Returns `true` if this is a `Cte` reference.
56    pub fn is_cte(&self) -> bool {
57        matches!(self, Self::Cte { .. })
58    }
59}
60
61impl From<TableId> for TableRef {
62    fn from(value: TableId) -> Self {
63        Self::Table(value)
64    }
65}
66
67impl From<ExprArg> for TableRef {
68    fn from(value: ExprArg) -> Self {
69        TableRef::Arg(value)
70    }
71}
72
73impl PartialEq<TableId> for TableRef {
74    fn eq(&self, other: &TableId) -> bool {
75        self.references(*other)
76    }
77}