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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// # Database

// ## Prelude

#[cfg(feature = "no-std")] use alloc::string::String;
#[cfg(feature = "no-std")] use alloc::vec::Vec;
use core::fmt;
use table::{Value, Table, TableId, Index};
use indexes::TableIndex;
use hashbrown::hash_map::{HashMap, Entry};
use std::rc::Rc;
use std::cell::RefCell;

// ## Changes

#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub enum Change {
  Set{table: u64, row: Index, column: Index, value: Value},
  Remove{table: u64, row: Index, column: Index, value: Value},
  NewTable{id: u64, rows: u64, columns: u64},
  RenameColumn{table: u64, column_ix: u64, column_alias: u64},
  RemoveTable{id: u64, rows: u64, columns: u64},
}

impl fmt::Debug for Change {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      Change::Set{table, row, column, value} => write!(f, "<set> #{:#x} [{:?} {:?} {:?}]", table, row, column, value),
      Change::Remove{table, row, column, value} => write!(f, "<remove> #{:#x} [{:?} {:?}: {:?}]", table, row, column, value),
      Change::NewTable{id, rows, columns} => write!(f, "<newtable> #{:#x} [{:?} x {:?}]", id, rows, columns),
      Change::RenameColumn{table, column_ix, column_alias} => write!(f, "<renamecolumn> #{:#x} {:#x} -> {:#x}", table, column_ix, column_alias),
      Change::RemoveTable{id, rows, columns} => write!(f, "<removetable> #{:#x} [{:?} x {:?}]", id, rows, columns),
    }
  }
}
  
// ## Transaction

#[derive(Clone, Serialize, Deserialize)]
pub struct Transaction {
  pub tables: Vec<Change>,
  pub adds: Vec<Change>,
  pub removes: Vec<Change>,
  pub names: Vec<Change>,
}

impl Transaction {
  pub fn new() -> Transaction {
    Transaction {
      tables: Vec::new(),
      adds: Vec::new(),
      removes: Vec::new(),
      names: Vec::new(),
    }
  }

  pub fn from_changeset(changes: Vec<Change>) -> Transaction {
    let mut txn = Transaction::new();
    for change in changes {
      match change {
        Change::Set{..} => txn.adds.push(change),
        Change::Remove{..} => txn.removes.push(change),
        Change::RemoveTable{..} |
        Change::NewTable{..} => txn.tables.push(change),
        Change::RenameColumn{..} => txn.names.push(change),
      }
    }
    txn
  }

  pub fn from_change(change: Change) -> Transaction {
    let mut txn = Transaction::new();
    match change {
      Change::Set{..} => txn.adds.push(change),
      Change::Remove{..} => txn.removes.push(change),
      Change::RemoveTable{..} |
      Change::NewTable{..} => txn.tables.push(change),
      Change::RenameColumn{..} => txn.names.push(change),
    }
    txn
  }

  pub fn from_adds_removes(adds: Vec<(u64, Index, Index, String)>, removes: Vec<(u64, Index, Index, String)>) -> Transaction {
    let mut txn = Transaction::new();
    for (table, row, column, value) in adds {
      txn.adds.push(Change::Set{table, row, column, value: Value::from_string(value)});
    }
    for (table, row, column, value) in removes {
      txn.removes.push(Change::Remove{table, row, column, value: Value::from_string(value)});
    }
    txn    
  }

}

impl fmt::Debug for Transaction {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    for ref table in &self.tables {
      write!(f, "{:?}\n", table).unwrap();
    }
    for ref add in &self.adds {
      write!(f, "{:?}\n", add).unwrap();
    }
    for ref remove in &self.removes {
      write!(f, "{:?}\n", remove).unwrap();
    }
    for ref name in &self.names {
      write!(f, "{:?}\n", name).unwrap();
    }
    Ok(())
  }
}

// ## Interner

#[derive(Debug, Clone)]
pub struct Interner {
  pub offset: usize,
  pub tables: TableIndex,
  pub names: HashMap<u64,String>,
  pub changes: Vec<Change>,
  pub changes_count: usize,
  pub change_pointer: usize, // points at the next available slot in memory that can hold a change
  pub rollover: usize,
  pub last_round: usize,
}

impl Interner {

  pub fn new(change_capacity: usize, table_capacity: usize) -> Interner {
    Interner {
      offset: 0,
      tables: TableIndex::new(table_capacity),
      names: HashMap::new(),
      changes: Vec::with_capacity(change_capacity),
      changes_count: 0,
      change_pointer: 0,
      rollover: 0,
      last_round: 0,
    }
  }

  pub fn clear(&mut self) {
    self.tables.clear();
    self.changes.clear();
    self.changes_count = 0;
    self.change_pointer = 0;
  }

  pub fn process_transaction(&mut self, txn: &Transaction) {
    // First make any tables
    for table in txn.tables.iter() {
      self.intern_change(table);
    }
    // Change names
    for name in txn.names.iter() {
      self.intern_change(name);
    }
    // Handle the removes
    for remove in txn.removes.iter() {
      self.intern_change(remove);
    }
    // Handle the adds
    for add in txn.adds.iter() {
      self.intern_change(add);
    }    
  }

  fn intern_change(&mut self, change: &Change) { 
    match change {
      Change::Set{table, row, column, value} => {
        let mut changed = false;
        let mut alias: Option<u64> = None;
        match self.tables.get(*table) {
          Some(table_ref) => {
            alias = table_ref.borrow().get_column_alias(column);
            let old_value = table_ref.borrow_mut().set_cell(&row, &column, value.clone());
            if old_value != *value {
              changed = true;
            }
            if self.offset == 0 && changed == true {
              match old_value {
                Value::Empty => (),
                // Save a remove so that we can rewind
                _ => self.save_change(&Change::Remove{table: *table, row: row.clone(), column: column.clone(), value: old_value}),
              }
            }
            
          }
          None => (),
        };
        if changed == true {
          match alias {
            Some(id) => {
              self.tables.changed_this_round.insert((table.clone(), Index::Alias(id)))
            },
            _ => false,
          };
          self.tables.changed_this_round.insert((table.clone(), column.clone()));
          self.tables.changed_this_round.insert((table.clone(), Index::Index(0)));
        }
      },
      Change::Remove{table, row, column, value} => {
        /*
        match value {
          Value::Empty => (),
          _ => {
            match self.tables.get_mut(*table) {
              Some(table_ref) => {
                table_ref.set_cell_by_id(*row as usize, *column as usize, Value::Empty);
              }
              None => (),
            };            
          },
        };
        self.tables.changed_this_round.insert((*table as usize, *column as usize));
        */
      },
      Change::NewTable{id, rows, columns } => {
        self.tables.insert(Table::new(*id, *rows, *columns));
      }
      Change::RemoveTable{id, rows: _, columns: _} => {
        self.tables.remove(&id);
      }
      Change::RenameColumn{table, column_ix, column_alias} => { 
        match self.tables.get(*table) {
          Some(table_ref) => {
            table_ref.borrow_mut().set_column_alias(*column_alias, *column_ix);
          }
          None => (),
        };
        self.tables.changed_this_round.insert((*table, Index::Alias(*column_alias)));
      },
    }
    if self.offset == 0 {
      self.save_change(change);
    }    
  }

  // Save the change. If there's enough room in memory, store it there. 
  // If not, make room by evicting some old change and throw that on disk. 
  // For now, we'll make the policy that the oldest record get evicted first.
  fn save_change(&mut self, change: &Change) {
    if self.changes.len() < self.changes.capacity() {
      self.changes.push(change.clone());
    } else if self.change_pointer == self.changes.capacity() {
      self.change_pointer = 0;
      self.rollover += 1;
      self.changes[self.change_pointer] = change.clone();
    } else {
      self.changes[self.change_pointer] = change.clone();
    }
    self.change_pointer += 1;
    self.changes_count += 1;
  }

  pub fn get_table(&self, table: u64) -> Option<&Rc<RefCell<Table>>> {
    self.tables.get(table)
  }

  pub fn contains(&mut self, table: TableId) -> bool {
    self.tables.contains(*table.unwrap())
  }

  pub fn get_column(&self, table: TableId, column: Index) -> Option<&Vec<Value>> {
    match self.tables.get(*table.unwrap()) {
      Some(stored_table) => {
        match unsafe{(*stored_table.as_ptr()).get_column(&column)} {
          Some(column) => Some(column),
          None => None,
        }
      },
      None => None,
    }
  }

  /*
  pub fn get_cell(&self, table: u64, row_ix: usize, column_ix: usize) -> Option<&Value> {
    match self.tables.get(table) {
      Some(stored_table) => {
        stored_table.index(row_ix, column_ix)
      },
      None => None,
    }
  }*/

  pub fn len(&self) -> usize {
    self.changes_count as usize
  }

}