geekorm_core/builder/
database.rs

1//! # GeekORM Database
2use serde::{Deserialize, Serialize};
3
4use super::table::Table;
5use crate::Column;
6
7/// GeekORM Database
8#[derive(Debug, Default, Serialize, Deserialize)]
9pub struct Database {
10    /// The tables in the database
11    pub tables: Vec<Table>,
12}
13
14impl Database {
15    /// Find a table by name
16    pub fn get_table(&self, name: &str) -> Option<&Table> {
17        self.tables.iter().find(|table| table.name == name)
18    }
19
20    /// Get the column by table and column name
21    pub fn get_table_column(&self, table: &str, column: &str) -> Option<&Column> {
22        self.get_table(table)
23            .unwrap()
24            .columns
25            .columns
26            .iter()
27            .find(|col| col.name == column)
28    }
29
30    /// Get the list of table names
31    pub fn get_table_names(&self) -> Vec<&str> {
32        self.tables.iter().map(|t| t.name.as_str()).collect()
33    }
34
35    /// Get the list of columns for a table name
36    pub fn get_table_columns(&self, table: &str) -> Vec<&str> {
37        self.get_table(table)
38            .unwrap()
39            .columns
40            .columns
41            .iter()
42            .map(|col| col.name.as_str())
43            .collect()
44    }
45}
46
47#[cfg(feature = "migrations")]
48impl quote::ToTokens for Database {
49    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
50        // TODO: Support for multiple databases
51
52        // let name = self.name.clone();
53        // let name_ident = format_ident!("{}", name);
54        let tables = &self.tables;
55
56        tokens.extend(quote::quote! {
57            pub static ref Database: Box<geekorm::Database> = Box::new(
58                geekorm::Database {
59                    tables: Vec::from([
60                        #(#tables),*
61                    ])
62                }
63            );
64        });
65    }
66}