DataBases changes tracker introduced

+ TrackDatabase object wraps the Database and support commit/rollback
This commit is contained in:
romanman 2014-06-11 15:09:38 +01:00
parent 33af300619
commit 333849dac0
2 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package org.ethereum.db;
import java.util.Arrays;
/**
* www.ethereumJ.com
*
* @author: Roman Mandeleil
* Created on: 11/06/2014 15:02
*/
public class ByteArrayWrapper {
private final byte[] data;
public ByteArrayWrapper(byte[] data)
{
if (data == null)
{
throw new NullPointerException();
}
this.data = data;
}
@Override
public boolean equals(Object other)
{
if (!(other instanceof ByteArrayWrapper))
{
return false;
}
return Arrays.equals(data, ((ByteArrayWrapper)other).data);
}
@Override
public int hashCode()
{
return Arrays.hashCode(data);
}
public byte[] getData() {
return data;
}
}

View File

@ -0,0 +1,76 @@
package org.ethereum.db;
import java.util.HashMap;
import java.util.Map;
/**
* www.ethereumJ.com
*
* @author: Roman Mandeleil
* Created on: 11/06/2014 14:09
*/
public class TrackDatabase {
private Database db;
private boolean trackingChanges;
private Map<ByteArrayWrapper, byte[]> changes;
private Map<ByteArrayWrapper, byte[]> deletes;
public TrackDatabase(Database db) {
this.db = db;
}
public void startTrack(){
changes = new HashMap<>();
deletes = new HashMap<>();
trackingChanges = true;
}
public void commitTrack(){
for(ByteArrayWrapper key : changes.keySet()){
db.put(key.getData(), changes.get(key));
}
changes = null;
trackingChanges = false;
}
public void rollbackTrack(){
changes = new HashMap<>();
deletes = new HashMap<>();
changes = null;
trackingChanges = false;
}
public void put(byte[] key, byte[] value) {
if (trackingChanges){
changes.put( new ByteArrayWrapper(key) , value);
} else {
db.put(key, value);
}
}
public byte[] get(byte[] key) {
if(trackingChanges){
ByteArrayWrapper wKey = new ByteArrayWrapper(key);
if (deletes.get(wKey) != null) return null;
if (changes.get(wKey) != null) return changes.get(wKey);
return db.get(key);
}
return db.get(key);
}
/** Delete object (key) from db **/
public void delete(byte[] key) {
if (trackingChanges){
ByteArrayWrapper wKey = new ByteArrayWrapper(key);
deletes.put(wKey, null);
} else {
db.delete(key);
}
}
}