Skip to main content

toasty_core/schema/db/
schema.rs

1use super::{Column, ColumnId, Index, IndexId, Table, TableId};
2
3/// The complete database-level schema: a collection of tables.
4///
5/// Provides indexed access to tables, columns, and indices by their IDs.
6///
7/// # Examples
8///
9/// ```ignore
10/// use toasty_core::schema::db::Schema;
11///
12/// let schema = Schema::default();
13/// assert!(schema.tables.is_empty());
14/// ```
15#[derive(Debug, Default, Clone)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct Schema {
18    /// All tables in this schema.
19    pub tables: Vec<Table>,
20}
21
22impl Schema {
23    /// Returns the column identified by `id`.
24    ///
25    /// # Panics
26    ///
27    /// Panics if the table or column index is out of bounds.
28    pub fn column(&self, id: impl Into<ColumnId>) -> &Column {
29        let id = id.into();
30        self.table(id.table)
31            .columns
32            .get(id.index)
33            .expect("invalid column ID")
34    }
35
36    /// Returns the index identified by `id`.
37    ///
38    /// # Panics
39    ///
40    /// Panics if the table or index offset is out of bounds.
41    // NOTE: this is unlikely to confuse users given the context.
42    #[allow(clippy::should_implement_trait)]
43    pub fn index(&self, id: IndexId) -> &Index {
44        self.table(id.table)
45            .indices
46            .get(id.index)
47            .expect("invalid index ID")
48    }
49
50    /// Returns the table identified by `id`.
51    ///
52    /// # Panics
53    ///
54    /// Panics if the table index is out of bounds.
55    pub fn table(&self, id: impl Into<TableId>) -> &Table {
56        self.tables.get(id.into().0).expect("invalid table ID")
57    }
58
59    /// Returns a mutable reference to the table identified by `id`.
60    ///
61    /// # Panics
62    ///
63    /// Panics if the table index is out of bounds.
64    pub fn table_mut(&mut self, id: impl Into<TableId>) -> &mut Table {
65        self.tables.get_mut(id.into().0).expect("invalid table ID")
66    }
67}