Skip to main content

toasty_core/stmt/
table_ref.rs

1use crate::stmt::{ExprArg, ExprFunc, 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, a set of table functions, 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    /// Table functions evaluated in parallel using SQL `ROWS FROM`.
40    RowsFrom(Vec<ExprFunc>),
41
42    /// A placeholder that will be replaced with a derived table at a later
43    /// compilation stage.
44    Arg(ExprArg),
45}
46
47impl TableRef {
48    /// Returns `true` if this ref points to the given schema table.
49    pub fn references(&self, table_id: TableId) -> bool {
50        match self {
51            Self::Cte { .. } => false,
52            Self::Derived { .. } => false,
53            Self::Table(id) => id == &table_id,
54            Self::RowsFrom(_) => false,
55            Self::Arg { .. } => todo!(),
56        }
57    }
58
59    /// Returns `true` if this is a `Cte` reference.
60    pub fn is_cte(&self) -> bool {
61        matches!(self, Self::Cte { .. })
62    }
63}
64
65impl From<TableId> for TableRef {
66    fn from(value: TableId) -> Self {
67        Self::Table(value)
68    }
69}
70
71impl From<ExprArg> for TableRef {
72    fn from(value: ExprArg) -> Self {
73        TableRef::Arg(value)
74    }
75}
76
77impl PartialEq<TableId> for TableRef {
78    fn eq(&self, other: &TableId) -> bool {
79        self.references(*other)
80    }
81}