Skip to main content

sql_rs/types/
schema.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4pub enum ColumnType {
5    Integer,
6    Float,
7    Text,
8    Blob,
9    Boolean,
10}
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct Column {
14    pub name: String,
15    pub column_type: ColumnType,
16    pub nullable: bool,
17    pub primary_key: bool,
18}
19
20impl Column {
21    pub fn new(name: impl Into<String>, column_type: ColumnType) -> Self {
22        Self {
23            name: name.into(),
24            column_type,
25            nullable: true,
26            primary_key: false,
27        }
28    }
29    
30    pub fn primary_key(mut self) -> Self {
31        self.primary_key = true;
32        self.nullable = false;
33        self
34    }
35    
36    pub fn not_null(mut self) -> Self {
37        self.nullable = false;
38        self
39    }
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct Schema {
44    pub table_name: String,
45    pub columns: Vec<Column>,
46}
47
48impl Schema {
49    pub fn new(table_name: impl Into<String>) -> Self {
50        Self {
51            table_name: table_name.into(),
52            columns: Vec::new(),
53        }
54    }
55    
56    pub fn add_column(mut self, column: Column) -> Self {
57        self.columns.push(column);
58        self
59    }
60    
61    pub fn get_column(&self, name: &str) -> Option<&Column> {
62        self.columns.iter().find(|c| c.name == name)
63    }
64    
65    pub fn primary_key(&self) -> Option<&Column> {
66        self.columns.iter().find(|c| c.primary_key)
67    }
68}