otter_sql/
database.rs

1//! Databases.
2
3use crate::{schema::Schema, BoundedString};
4
5const DEFAULT_SCHEMA_NAME: &str = "main";
6
7/// An in-memory database.
8///
9/// Note: you will need a [`VirtualMachine`](`crate::vm::VirtualMachine`)
10/// to execute queries on a database.
11pub struct Database {
12    name: BoundedString,
13    schemas: Vec<Schema>,
14}
15
16impl Database {
17    pub fn new(name: BoundedString) -> Self {
18        Self {
19            name,
20            // the default schema needs to be the first
21            schemas: vec![Schema::new(DEFAULT_SCHEMA_NAME.into())],
22        }
23    }
24
25    /// Add a new schema.
26    pub fn add_schema(&mut self, schema: Schema) -> &mut Self {
27        self.schemas.push(schema);
28        self
29    }
30
31    /// The name of the database.
32    pub fn name(&self) -> &BoundedString {
33        &self.name
34    }
35
36    /// All the schemas in the database.
37    pub fn schemas(&self) -> &Vec<Schema> {
38        &self.schemas
39    }
40
41    /// The default schema.
42    pub fn default_schema(&self) -> &Schema {
43        // ensure that the default schema is always the first
44        &self.schemas[0]
45    }
46
47    /// Mutable reference to the default schema.
48    pub fn default_schema_mut(&mut self) -> &mut Schema {
49        // ensure that the default schema is always the first
50        &mut self.schemas[0]
51    }
52
53    pub fn schema_by_name(&self, name: &BoundedString) -> Option<&Schema> {
54        self.schemas().iter().find(|s| s.name() == name)
55    }
56
57    pub fn schema_by_name_mut(&mut self, name: &BoundedString) -> Option<&mut Schema> {
58        self.schemas.iter_mut().find(|s| s.name() == name)
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use crate::schema::Schema;
65
66    use super::{Database, DEFAULT_SCHEMA_NAME};
67
68    #[test]
69    fn create_database() {
70        let mut db = Database::new("test".into());
71
72        assert_eq!(db.name(), "test");
73        assert_eq!(db.schemas().len(), 1);
74        assert_eq!(db.schemas()[0].name(), DEFAULT_SCHEMA_NAME);
75        assert_eq!(db.schemas()[0].tables().len(), 0);
76
77        db.add_schema(Schema::new("test".into()));
78        assert_eq!(db.schemas().len(), 2);
79        assert_eq!(db.schemas()[1].name(), "test");
80        assert_eq!(db.schemas()[1].tables().len(), 0);
81    }
82}