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 a mutable reference to the column identified by `id`.
37 ///
38 /// # Panics
39 ///
40 /// Panics if the table or column index is out of bounds.
41 pub fn column_mut(&mut self, id: impl Into<ColumnId>) -> &mut Column {
42 let id = id.into();
43 self.table_mut(id.table)
44 .columns
45 .get_mut(id.index)
46 .expect("invalid column ID")
47 }
48
49 /// Returns the index identified by `id`.
50 ///
51 /// # Panics
52 ///
53 /// Panics if the table or index offset is out of bounds.
54 // NOTE: this is unlikely to confuse users given the context.
55 #[allow(clippy::should_implement_trait)]
56 pub fn index(&self, id: IndexId) -> &Index {
57 self.table(id.table)
58 .indices
59 .get(id.index)
60 .expect("invalid index ID")
61 }
62
63 /// Returns a mutable reference to the index identified by `id`.
64 ///
65 /// # Panics
66 ///
67 /// Panics if the table or index offset is out of bounds.
68 // NOTE: this is unlikely to confuse users given the context.
69 #[allow(clippy::should_implement_trait)]
70 pub fn index_mut(&mut self, id: IndexId) -> &mut Index {
71 self.table_mut(id.table)
72 .indices
73 .get_mut(id.index)
74 .expect("invalid index ID")
75 }
76
77 /// Returns the table identified by `id`.
78 ///
79 /// # Panics
80 ///
81 /// Panics if the table index is out of bounds.
82 pub fn table(&self, id: impl Into<TableId>) -> &Table {
83 self.tables.get(id.into().0).expect("invalid table ID")
84 }
85
86 /// Returns a mutable reference to the table identified by `id`.
87 ///
88 /// # Panics
89 ///
90 /// Panics if the table index is out of bounds.
91 pub fn table_mut(&mut self, id: impl Into<TableId>) -> &mut Table {
92 self.tables.get_mut(id.into().0).expect("invalid table ID")
93 }
94}