1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use crate::*;
use hashbrown::{HashMap, HashSet};
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt;

#[derive(Clone, Serialize, Deserialize)]
pub enum Change {
  Set((u64, Vec<(TableIndex, TableIndex, Value)>)),
  NewTable{table_id: u64, rows: usize, columns: usize},
  ColumnAlias{table_id: u64, column_ix: usize, column_alias: u64},
  ColumnKind{table_id: u64, column_ix: usize, column_kind: ValueKind},
}

impl fmt::Debug for Change {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      Change::Set((table_id,args)) => write!(f,"Set({},{:#?})",humanize(table_id),args)?,
      Change::NewTable{table_id,rows,columns} => write!(f,"NewTable({},{:?},{:?})",humanize(table_id),rows,columns)?,
      Change::ColumnAlias{table_id,column_ix,column_alias} => write!(f,"ColumnAlias({},{:?},{})",humanize(table_id),column_ix,humanize(column_alias))?,
      Change::ColumnKind{table_id,column_ix,column_kind} => write!(f,"ColumnKind({},{:?},{:?})",humanize(table_id),column_ix,column_kind)?,
    }
    Ok(())
  }
}

pub type Transaction = Vec<Change>;

#[derive(Clone)]
pub struct Database {
  pub dynamic_tables: HashSet<(TableId,RegisterIndex,RegisterIndex)>,
  pub tables: HashMap<u64,Rc<RefCell<Table>>>,
  pub table_alias_to_id: HashMap<u64,TableId>,
}

impl Database {
  pub fn new() -> Database {
    Database {
      dynamic_tables: HashSet::new(),
      tables: HashMap::new(),
      table_alias_to_id: HashMap::new(),
    }
  }

  pub fn clear(&mut self) {
    self.dynamic_tables.clear();
    self.tables.clear();
    self.table_alias_to_id.clear();
  }

  pub fn union(&mut self, other: &Self) -> Result<(),MechError> {
    let mut other_tables = other.tables.clone();
    for (id,other_table) in other_tables.drain() {
      match self.tables.try_insert(id, other_table.clone()) {
        Ok(_) => (),
        Err(x) => {return Err(MechError{msg: "".to_string(), id: 1723, kind: MechErrorKind::None});},
      }
    }
    let mut other_table_aliases = other.table_alias_to_id.clone();
    for (id,other_table) in other_table_aliases.drain() {
      match self.table_alias_to_id.try_insert(id, other_table.clone()) {
        Ok(_) => (),
        Err(x) => {return Err(MechError{msg: "".to_string(), id: 1724, kind: MechErrorKind::None});},
      }
    }
    Ok(())
  }

  pub fn insert_alias(&mut self, alias: u64, table_id: TableId) -> Result<TableId,MechError> {
    match self.table_alias_to_id.try_insert(alias, table_id) {
      Err(x) => {return Err(MechError{msg: "".to_string(), id: 1725, kind: MechErrorKind::DuplicateAlias(*table_id.unwrap())});},
      Ok(x) => Ok(*x), 
    }
  }

  pub fn insert_table(&mut self, table: Table) -> Result<Rc<RefCell<Table>>,MechError> {
    match self.tables.try_insert(table.id, Rc::new(RefCell::new(table))) {
      Ok(x) => Ok(x.clone()),
      Err(x) => {return Err(MechError{msg: "".to_string(), id: 1726, kind: MechErrorKind::None});},
    }
  }

  pub fn overwrite_table(&mut self, table: Table) -> Result<Rc<RefCell<Table>>,MechError> {
    match self.tables.insert(table.id, Rc::new(RefCell::new(table))) {
      Some(x) => Ok(x.clone()),
      None => {return Err(MechError{msg: "".to_string(), id: 1726, kind: MechErrorKind::None});},
    }
  }

  pub fn insert_table_ref(&mut self, table: TableRef) -> Result<Rc<RefCell<Table>>,MechError> {
    let table_id = {
      let table_brrw = table.borrow();
      table_brrw.id
    };
    match self.tables.try_insert(table_id, table) {
      Ok(x) => Ok(x.clone()),
      Err(x) => {return Err(MechError{msg: "".to_string(), id: 1726, kind: MechErrorKind::None});},
    }
  }

  pub fn get_table(&self, table_name: &str) -> Option<&Rc<RefCell<Table>>> {
    let alias = hash_str(table_name);
    match self.table_alias_to_id.get(&alias) {
      Some(table_id) => {
        self.tables.get(table_id.unwrap())
      }
      _ => self.tables.get(&alias),
    }
  }

  pub fn get_table_by_id(&self, table_id: &u64) -> Option<&Rc<RefCell<Table>>> {
    match self.tables.get(table_id) {
      None => {
        match self.table_alias_to_id.get(table_id) {
          None => None,
          Some(table_id) => {
            self.tables.get(table_id.unwrap())
          }
        }
      }
      x => x
    }
  }

  pub fn get_table_by_id_mut(&self, table_id: u64) -> Option<&Rc<RefCell<Table>>> {
    let table_id = match self.tables.contains_key(&table_id) {
      true => table_id,
      false => match self.table_alias_to_id.get(&table_id) {
        Some(table_id) => *table_id.unwrap(),
        None => return None,
      }
    };
    self.tables.get(&table_id)
  }
}

impl fmt::Debug for Database {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    let mut db_drawing = BoxPrinter::new();
    db_drawing.add_header("tables");
    for table in self.tables.values() {
      db_drawing.add_line(format!("{:?}", table.borrow()));
    }
    if self.table_alias_to_id.len() > 0 {
      db_drawing.add_header("table alias → table id");
      for (alias,id) in self.table_alias_to_id.iter() {
        db_drawing.add_line(format!("{} → {:?}", humanize(alias), id));
      }
    }
    write!(f,"{:?}",db_drawing)?;
    Ok(())
  }
}