Permalink
Browse files

Added indexing and unique key constraint

  • Loading branch information...
1 parent c255dcf commit 28087f669966537f453b47a5f669aaaa06f3310d @kriszyp kriszyp committed Jan 25, 2010
Showing with 58 additions and 2 deletions.
  1. +2 −2 lib/store/js-file.js
  2. +56 −0 lib/store/memory.js
View
@@ -23,13 +23,13 @@ exports.JSFile = function(filename){
var fileTime = stat.mtime.getTime();
if(fileTime > lastMod){
lastMod = fileTime;
- store.index = JSONExt.parse(File.read(filename));
+ store.setIndex(JSONExt.parse(File.read(filename)));
}
}
else if(lastMod === 0){
// node goes in here right now
try{
- store.index = JSONExt.parse(File.read(filename).wait());
+ store.setIndex(JSONExt.parse(File.read(filename).wait()));
}catch(e){
// if it doesn't exist, node throws an error
}
View
@@ -5,14 +5,70 @@
var ReadonlyMemory = require("./readonly-memory").ReadonlyMemory;
exports.Memory = function(options){
var store = ReadonlyMemory(options);
+ var uniqueKeys = {};
// start with the read-only memory store and add write support
store.put = function(object, id){
object.id = id = id || object.id || Math.round(Math.random()*10000000000000);
+ updateIndexes.call(this, id, object);
this.index[id] = object;
return id;
};
store["delete"] = function(id){
+ updateIndexes.call(this, id);
delete this.index[id];
};
+ store.setSchema = function(schema){
+ for(var i in schema.properties){
+ if(schema.properties[i].unique){
+ uniqueKeys[i] = true;
+ store.indexes[i] = {};
+ }
+ }
+ };
+ store.indexes = {};
+ store.setIndex = function(index){
+ this.index = index;
+ for(var id in index){
+ updateIndexes.call(this, id, index[id]);
+ }
+ };
+ store.setIndex(store.index);
return store;
+
+ function updateIndexes(id, object){
+ var indexes = this.indexes;
+ var current = this.index[id];
+ // update the indexes
+ for(var i in indexes){
+ var index = indexes[i];
+ if(uniqueKeys.hasOwnProperty(i)){
+ if(current){
+ delete index[current[i]];
+ }
+ if(object){
+ if(index.hasOwnProperty(object[i])){
+ throw new Error("Unique key constraint error duplicate " + object[i] + " for key " + i);
+ }
+ index[object[i]] = object;
+ }
+ }
+ else{
+ // multi-valued indexes, each entry is an array
+ if(current){
+ var forKey = index[current[i]];
+ if(forKey){
+ var position = forKey.indexOf(current);
+ if(position > -1){
+ forKey.splice(position, 1);
+ }
+ }
+ }
+ if(object){
+ (index[object[i]] = index[object[i]] || []).push(object);
+ }
+ }
+ }
+
+ }
+
};

0 comments on commit 28087f6

Please sign in to comment.