Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

first commit

  • Loading branch information...
commit d8a2cd85311f6ba170e21c23dc03faa7a0f7a30c 0 parents
@Pita authored
2  .gitignore
@@ -0,0 +1,2 @@
+var/*.db*
+*~
202 LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
364 benchmark.js
@@ -0,0 +1,364 @@
+/**
+ * 2011 Peter 'Pita' Martischka
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS-IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var async = require("async");
+var ueberDB = require("./ueberDB");
+
+//settings
+var maxValues = 100000;
+var writes = 210;
+var reads = 100;
+var updates = 20;
+var deletes = 10;
+var initialWrites = writes-deletes;
+var valueLength = 1000;
+var randomized = true;
+
+var db;
+
+//counts how man keys are in the db
+var counter = 0;
+var timeSum = null;
+var randomStrings = [];
+var valueMap = {};
+
+//the default settings for benchmarking
+var bench_settings = {};
+bench_settings["mysql"] = {"user":"root", host: "localhost", "password":"", database: "store"};
+bench_settings["sqlite"] = {filename:"var/sqlite3.db"};
+
+if(process.argv.length == 3)
+{
+ var settings = bench_settings[process.argv[2]];
+ db = new ueberDB.database(process.argv[2], settings);
+
+ benchmark(function(err, time)
+ {
+ if(err) console.error(err.stack ? err.stack : err);
+ console.log("finished");
+ console.log("time: " + time + "s");
+ process.exit(0);
+ })
+}
+
+//the benchmark function
+function benchmark(callback)
+{
+ var startTime = new Date().getTime();
+
+ console.log("generating random data, to fill database...");
+ for(var i=0;i<1000;i++)
+ {
+ randomStrings.push(randomString(valueLength));
+ }
+ console.log("done");
+
+ async.waterfall([
+ //init db
+ function(callback)
+ {
+ console.log("initalize database...");
+ db.init(callback);
+ },
+ //fill the database with the inital values
+ function(callback)
+ {
+ console.log("done");
+
+ console.log("do the first writings to fill the database...");
+ doOperations(generateOperations(counter, counter + initialWrites, initialWrites, "write"), false, callback);
+
+ //increment counter
+ counter+=initialWrites;
+ },
+ function(callback)
+ {
+ console.log("done");
+
+ console.error("values;read_time;write_time;update_time;delete_time;memory_mb");
+
+ var round = 1;
+
+ //async while loop
+ async.whilst(
+ function () { return counter < maxValues; },
+ function (callback)
+ {
+ if(round%50 == 0)
+ {
+ console.log("persistence test");
+ persistenceTest(callback);
+ round++;
+ return;
+ }
+ else
+ {
+ if(timeSum != null)
+ {
+ var readTime = Math.round(timeSum["read"]/reads);
+ var writeTime = Math.round(timeSum["write"]/writes);
+ var updateTime = Math.round(timeSum["update"]/updates);
+ var deleteTime = Math.round(timeSum["delete"]/deletes);
+ var memoryUsage = Math.round(process.memoryUsage().heapUsed/1024/1024);
+
+ var csvLine = counter + ";" + readTime + ";" + writeTime + ";" + updateTime + ";" + deleteTime + ";" + memoryUsage;
+
+ console.error(csvLine);
+ console.log("rows: " + counter);
+
+ //increment counter
+ counter+=writes-deletes;
+ }
+
+ timeSum = {"read":0, "write":0,"update":0,"delete":0};
+
+ var writeOps = generateOperations(counter, counter + writes, writes, "write");
+ var readOps = generateOperations(0, counter, reads, "read");
+ var updateOps = generateOperations(0, counter, updates, "update");
+ var deleteOps = generateOperations(0, counter, deletes, "delete");
+
+ if(randomized)
+ {
+ //put all operations together and shuffle them
+ var operations = writeOps.concat(readOps,updateOps,deleteOps).sort(function() {return 0.5 - Math.random()});
+
+ //execute the operations
+ doOperations(operations, true, callback);
+ }
+ else
+ {
+ async.waterfall([
+ function(callback)
+ {
+ console.error("write");
+ doOperations(writeOps, true, callback);
+ },
+ function(callback)
+ {
+ console.error("read");
+ doOperations(readOps, true, callback);
+ },
+ function(callback)
+ {
+ console.error("update");
+ doOperations(updateOps, true, callback);
+ },
+ function(callback)
+ {
+ console.error("delete");
+ doOperations(deleteOps, true, callback);
+ },
+ ],callback);
+ }
+ }
+
+ round++;
+ },callback);
+ }
+ ], function(err)
+ {
+ db.close(function()
+ {
+ var time = Math.round((new Date().getTime()-startTime)/1000);
+ callback(err, time);
+ });
+ });
+}
+
+function generateOperations(startNum, endNum, size, type)
+{
+ var operations = [];
+
+ var keyNum = startNum;
+
+ for(var i=0;i<size;i++)
+ {
+ var key;
+ if(type == "write")
+ {
+ key = "key" + keyNum;
+ keyNum++;
+ }
+ else
+ {
+ key = "key" + (startNum + uniqueRandomNum(endNum-startNum))
+ }
+
+ var operation = {type:type, key:key};
+
+ if(type == "write" || type == "update")
+ {
+ var StringNum = Math.floor(Math.random() * 1000);
+ operation.value = randomStrings[StringNum];
+ valueMap[key] = StringNum;
+ }
+
+ if(type == "delete")
+ {
+ valueMap[key] = null;
+ }
+
+ operations.push(operation);
+ }
+
+ return operations;
+}
+
+function doOperations(operations, measure, callback)
+{
+ async.forEach(operations, function(item, callback)
+ {
+ //if write or update, call set
+ if(item.type == "write" || item.type == "update")
+ {
+ if(measure)
+ {
+ measureTime(function(callback)
+ {
+ db.set(item.key, item.value, callback);
+ },item.type, callback);
+ }
+ else
+ {
+ db.set(item.key, item.value, callback);
+ }
+ }
+ else if(item.type == "read")
+ {
+ if(measure)
+ {
+ measureTime(function(callback){
+ db.get(item.key, callback);
+ },item.type, callback);
+ }
+ else
+ {
+ db.get(item.key, callback);
+ }
+ }
+ else if(item.type == "delete")
+ {
+ if(measure)
+ {
+ measureTime(function(callback){
+ db.remove(item.key, callback);
+ },item.type, callback);
+ }
+ else
+ {
+ db.remove(item.key, callback);
+ }
+ }
+ else
+ {
+ callback("Unkown Operation!");
+ }
+ },function(err)
+ {
+ callback(err);
+ });
+}
+
+function persistenceTest(callback)
+{
+ //get all keys in a array
+ var keys = [];
+ for(var i in valueMap)
+ {
+ keys.push(i);
+ }
+
+ //test for inconsistence
+ async.forEach(keys, function(item, callback)
+ {
+ db.get(item, function(err, value)
+ {
+ if(!err)
+ {
+ if(value != randomStrings[valueMap[item]])
+ {
+ err = "Inconsistent key : '" + item + "'\n";
+ err+= "is : '" + value + "'\n";
+ err+= "should be : '" + randomStrings[valueMap[item]] + "'";
+ }
+ }
+
+ callback(err);
+ });
+ }, callback);
+}
+
+function measureTime(func, type, callback){
+ var startTime = new Date().getTime();
+
+ func(function(err){
+ var time = new Date().getTime()-startTime;
+ timeSum[type]+=time;
+
+ callback(err);
+ });
+}
+
+var lastRands = [];
+
+// This Function ensures that the generated random values for the
+// deletes/updates are never the same in one round
+function uniqueRandomNum(maxNum)
+{
+ var rand;
+ var isUnique = false;
+
+ while(!isUnique)
+ {
+ rand = Math.floor(Math.random() * maxNum);
+
+ isUnique = true;
+
+ //try to proof that its not unique
+ for(var i in lastRands)
+ {
+ if(lastRands[i] == rand)
+ {
+ isUnique = false;
+ break;
+ }
+ }
+ }
+
+ lastRands.push(rand);
+
+ //remove the first element if lastRands is too long
+ if(lastRands.length > (reads+updates+deletes)*2)
+ {
+ lastRands.shift();
+ }
+
+ return rand;
+}
+
+function randomString(string_length)
+{
+ var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
+ var randomstring = '';
+
+ for (var i=0; i<string_length; i++)
+ {
+ var rnum = Math.floor(Math.random() * chars.length);
+ randomstring += chars.substring(rnum,rnum+1);
+ }
+
+ return randomstring;
+}
342 dbWrapper.js
@@ -0,0 +1,342 @@
+/**
+ * 2011 Peter 'Pita' Martischka
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS-IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+This module is made for the case, you want to use a SQL-Based Databse or a KeyValue Database that can only save strings(and no objects), as a JSON KeyValue Store.
+
+The idea of the dbWrapper is to provide following features:
+
+* automatic JSON serialize/deserialize to abstract that away from the database driver and the module user.
+* cache reads. A amount of KeyValues are hold in the memory, so that reading is faster.
+* Buffer DB Writings. Sets and deletes should be buffered to make them in a setted interval with a bulk. This reduces the overhead of database transactions and makes the database faster. But there is also a danger to loose data integrity, to keep that, we should provide a flush function.
+
+All Features can be disabled or configured. The Wrapper provides default settings that can be overwriden by the driver and by the module user.
+*/
+
+var defaultSettings =
+{
+ //the number of elements that should be cached. To Disable cache just set it to zero
+ cache: 1000,
+ //the interval in ms the wrapper writes to the database. To Disable interval writes just set it to zero
+ writeInterval: 100,
+ //a flag if the data sould be serialized/deserialized to json
+ json:true
+}
+
+/**
+ The constructor of the wrapper
+ @param wrappedDB The Database that should be wrapped
+ @param settings (optional) The settings that should be applied to the wrapper
+*/
+exports.database = function(wrappedDB, settings)
+{
+ //saved the wrappedDB
+ this.wrappedDB=wrappedDB;
+
+ //apply default settings
+ this.settings = {};
+ this.settings.cache = defaultSettings.cache;
+ this.settings.writeInterval = defaultSettings.writeInterval;
+ this.settings.json = defaultSettings.json;
+
+ //try to apply the settings of the driver
+ if(wrappedDB.settings != null)
+ {
+ if(wrappedDB.settings.cache != null) this.settings.cache = wrappedDB.settings.cache;
+ if(wrappedDB.settings.writeInterval != null) this.settings.writeInterval = wrappedDB.settings.writeInterval;
+ if(wrappedDB.settings.json != null) this.settings.json = wrappedDB.settings.json;
+ }
+
+ //try to apply the settings given with the constructor
+ if(settings != null)
+ {
+ if(settings.cache != null) this.settings.cache = settings.cache;
+ if(settings.writeInterval != null) this.settings.writeInterval = settings.writeInterval;
+ if(settings.json != null) this.settings.json = settings.json;
+ }
+
+ //freeze the settings at this point
+ this.settings = Object.freeze(this.settings);
+
+ //start the write Interval
+ if(this.settings.writeInterval > 0)
+ {
+ setInterval(flush, this.settings.writeInterval, this);
+ }
+
+ //ensure the buffer is flushed before the application ends
+ process.on('exit', function ()
+ {
+ flush(this);
+ });
+};
+
+/**
+ key is the key of the keyValue Object
+ value is a object
+ {
+ value: the value of the keyValue object, contains only deserialized data
+ dirty: true or false, means if its already written to the database or not
+ callback: (optional) a array of callbacks that should be called once this value is written
+ timestamp: a timestamp that shows when this item was read or write the last time.
+ The Garbage collector needs this value
+ }
+*/
+exports.database.prototype.buffer = {};
+
+//the length of the Buffer.
+exports.database.prototype.bufferLength = 0;
+
+/**
+ wraps the init function of the original DB
+*/
+exports.database.prototype.init = function(callback)
+{
+ this.wrappedDB.init(callback);
+}
+
+/**
+ wraps the close function of the original DB
+*/
+exports.database.prototype.close = function(callback)
+{
+ this.wrappedDB.close(callback);
+}
+
+/**
+ Gets the value trough the wrapper.
+*/
+exports.database.prototype.get = function(key, callback)
+{
+ //if cache is enabled and data is in the cache, get the value from the cache
+ if(this.settings.cache > 0 && this.buffer[key])
+ {
+ this.buffer[key].timestamp = new Date().getTime();
+ callback(null, this.buffer[key].value);
+ }
+ //caching is disabled but its still in a dirty writing cache, so we have to get the value out of the cache too
+ else if(this.settings.cache == 0 && this.buffer[key] && this.buffer[key].dirty)
+ {
+ this.buffer[key].timestamp = new Date().getTime();
+ callback(null, this.buffer[key].value);
+ }
+ //get it direct
+ else
+ {
+ var self = this;
+
+ this.wrappedDB.get(key, function(err,value)
+ {
+ if(self.settings.json)
+ {
+ try
+ {
+ value = JSON.parse(value);
+ }
+ catch(e)
+ {
+ console.error("JSON-PROBLEM:" + value);
+ callback(e);
+ return;
+ }
+ }
+
+ //cache the value if caching is enabled
+ if(self.settings.cache > 0)
+ self.buffer[key] = {"value":value, dirty:false, timestamp: new Date().getTime()};
+
+ self.bufferLength++;
+
+ //call the garbage collector
+ self.gc();
+
+ callback(err,value);
+ });
+ }
+}
+
+/**
+ Sets the value trough the wrapper
+*/
+exports.database.prototype.set = function(key, value, callback)
+{
+ //writing cache is enabled, so simply write it into the buffer
+ if(this.settings.writeInterval > 0)
+ {
+ //initalize the buffer object if it not exists
+ if(!this.buffer[key])
+ {
+ this.buffer[key] = {};
+ this.bufferLength++;
+ }
+
+ //set the new values
+ this.buffer[key].value = value;
+ this.buffer[key].dirty = true;
+ this.buffer[key].timestamp = new Date().getTime();
+
+ //call the garbage collector
+ this.gc();
+
+ //initalize the callback array in the buffer object if it not exists.
+ //we need this as an array, cause the value may be many times overwritten bevors its finally written to the database,
+ //but all callbacks must be called
+ if(!this.buffer[key].callbacks)
+ this.buffer[key].callbacks=[];
+
+ //add this callback to the array
+ this.buffer[key].callbacks.push(callback);
+ }
+ //writecache is disabled, so we write directly to the database
+ else
+ {
+ //The value is null, means this no set operation, this is a remove operation
+ if(value==null)
+ {
+ this.wrappedDB.remove(key,callback);
+ }
+ //thats a correct value
+ else
+ {
+ //stringify the value if stringifying is enabled
+ if(this.settings.json == true)
+ value = JSON.stringify(value);
+
+ this.wrappedDB.set(key,value,callback);
+ }
+ }
+}
+
+/**
+ Removes the value trough the wrapper
+*/
+exports.database.prototype.remove = function(key, callback)
+{
+ //make a set to null out of it
+ this.set(key, null, callback);
+}
+
+/**
+ Garbage Collector of the cache
+*/
+exports.database.prototype.gc = function()
+{
+ //If the buffer size is under the settings size or cache is disabled -> return cause there is nothing to do
+ if(this.bufferLength < this.settings.cache || this.settings.cache == 0)
+ {
+ return;
+ }
+
+ //collect all values that are not dirty
+ var deleteCandidates = [];
+ for(var i in this.buffer)
+ {
+ if(this.buffer[i].dirty == false)
+ {
+ deleteCandidates.push({key: i, timestamp: this.buffer[i].timestamp});
+ }
+ }
+
+ if(deleteCandidates.length > 0)
+ {
+ //sort them based on the timestamp
+ deleteCandidates.sort(function(a,b){
+ return a.timestamp-b.timestamp;
+ });
+
+ //delete the half buffer
+ for(var i=0; i<(this.settings.cache/2) && i<deleteCandidates.length;i++)
+ {
+ delete this.buffer[deleteCandidates[i].key];
+ this.bufferLength--;
+ }
+ }
+ //There are no undirty values to delete, means we have to flush the cache
+ else
+ {
+ var self = this;
+
+ setTimeout(flush,0,this,function(err){
+ self.gc();
+ });
+ }
+}
+
+/**
+ Wrapes the flush function
+*/
+exports.database.prototype.flush = function(callback)
+{
+ flush(this,callback);
+}
+
+var transmissionNum = 0;
+
+/**
+ Writes all dirty values to the database
+*/
+function flush (db, callback)
+{
+ var operations = [];
+ var callbacks = [];
+
+ //run trough the buffer and search for dirty values
+ for(var i in db.buffer)
+ {
+ if(db.buffer[i].dirty == true)
+ {
+ //collect all data for the operation
+ var type = db.buffer[i].value == null ? "remove" : "set";
+ var key = i;
+ var value = db.buffer[i].value;
+
+ //stringify the value if stringifying is enabled
+ if(db.settings.json == true && value != null)
+ value = JSON.stringify(value);
+
+ //add the operation to the operations array
+ operations.push({"type":type, "key":key, "value":value});
+
+ //collect callbacks
+ callbacks = callbacks.concat(db.buffer[i].callbacks);
+
+ //clean callbacks
+ db.buffer[i].callbacks = [];
+ //set the dirty flag to false
+ db.buffer[i].dirty = false;
+ }
+ }
+
+ //send the bulk to the database driver and call the callbacks with the results
+ if(operations.length > 0)
+ {
+ var thistransmissionNum = transmissionNum;
+
+ transmissionNum++;
+
+ db.wrappedDB.doBulk(operations, function(err)
+ {
+ for(var i in callbacks)
+ {
+ callbacks[i](err);
+ }
+
+ if(callback) callback();
+ });
+
+ }
+}
+
134 mysql_db.js
@@ -0,0 +1,134 @@
+/**
+ * 2011 Peter 'Pita' Martischka
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS-IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var mysql = require("mysql");
+var async = require("async");
+
+exports.database = function(settings)
+{
+ this.db = new mysql.Client();
+
+ this.settings = settings;
+
+ if(this.settings.host != null)
+ this.db.host = this.settings.host;
+
+ if(this.settings.port != null)
+ this.db.port = this.settings.port;
+
+ if(this.settings.user != null)
+ this.db.user = this.settings.user;
+
+ if(this.settings.password != null)
+ this.db.password = this.settings.password;
+
+ if(this.settings.database != null)
+ this.db.database = this.settings.database;
+
+ this.settings.cache = 1000;
+ this.settings.writeInterval = 100;
+ this.settings.json = true;
+}
+
+exports.database.prototype.init = function(callback)
+{
+ var _this = this;
+
+ async.waterfall([
+ function(callback)
+ {
+ _this.db.connect(callback);
+ },
+ function(result, callback)
+ {
+ var sql = "CREATE TABLE IF NOT EXISTS `store` ( " +
+ "`key` VARCHAR( 100 ) NOT NULL , " +
+ "`value` TEXT NOT NULL , " +
+ "PRIMARY KEY ( `key` ) " +
+ ") ENGINE = INNODB;";
+ _this.db.query(sql,[],callback);
+ }
+ ],function(err, info){
+ callback(err);
+ });
+}
+
+exports.database.prototype.get = function (key, callback)
+{
+ var sql = this.db.format("SELECT `value` FROM `store` WHERE `key` = ?", [key]);
+ this.db.query(sql, [], function(err,results)
+ {
+ var value = null;
+
+ if(!err && results.length == 1)
+ {
+ value = results[0].value;
+ }
+
+ callback(err,value);
+ });
+}
+
+exports.database.prototype.set = function (key, value, callback)
+{
+ if(key.length > 100)
+ {
+ callback("Your Key can only be 100 chars");
+ }
+ else
+ {
+ this.db.query("REPLACE INTO `store` VALUES (?,?)", [key, value], function(err, info){
+ callback(err);
+ });
+ }
+}
+
+exports.database.prototype.remove = function (key, callback)
+{
+ this.db.query("DELETE FROM `store` WHERE `key` = ?", [key], callback);
+}
+
+exports.database.prototype.doBulk = function (bulk, callback)
+{
+ var sql = "START TRANSACTION;\n";
+ for(var i in bulk)
+ {
+ if(bulk[i].type == "set")
+ {
+ sql+="REPLACE INTO `store` VALUES (" + this.db.escape(bulk[i].key) + ", " + this.db.escape(bulk[i].value) + ");\n";
+ }
+ else if(bulk[i].type == "remove")
+ {
+ sql+="DELETE FROM `store` WHERE `key` = " + this.db.escape(bulk[i].key) + ";\n";
+ }
+ }
+ sql += "COMMIT;";
+
+ this.db.query(sql, function(err){
+ if(err)
+ {
+ console.error("ERROR WITH SQL: ");
+ console.error(sql);
+ }
+
+ callback(err);
+ });
+}
+
+exports.database.prototype.close = function(callback)
+{
+ this.db.end(callback);
+}
14 package.json
@@ -0,0 +1,14 @@
+{
+ "name" : "ueberDB",
+ "description" : "transform every database into a object key value store",
+ "url" : "https://github.com/Pita/ueberDB",
+ "keywords" : ["database", "keyvalue"],
+ "author" : "Peter 'Pita' Martischka <petermartischka@googlemail.com>",
+ "dependencies" : {
+ "mysql" : ">=0.9.1",
+ "sqlite3": ">=2.0.12",
+ "async" : ">=0.1.9"
+ }
+ "main" : "./ueberDB",
+ "version" : "0.0.1"
+}
117 sqlite_db.js
@@ -0,0 +1,117 @@
+/**
+ * 2011 Peter 'Pita' Martischka
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS-IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var sqlite3 = require("sqlite3");
+var async = require("async");
+
+exports.database = function(settings)
+{
+ this.db=null;
+
+ if(!settings || !settings.filename)
+ {
+ settings = {filename:":memory:"};
+ }
+
+ this.settings = settings;
+
+ //set settings for the dbWrapper
+ if(settings.filename == ":memory:")
+ {
+ this.settings.cache = 0;
+ this.settings.writeInterval = 0;
+ this.settings.json = true;
+ }
+ else
+ {
+ this.settings.cache = 1000;
+ this.settings.writeInterval = 100;
+ this.settings.json = true;
+ }
+}
+
+exports.database.prototype.init = function(callback)
+{
+ var _this = this;
+
+ async.waterfall([
+ function(callback)
+ {
+ _this.db = new sqlite3.cached.Database(_this.settings.filename, callback);
+ },
+ function(callback)
+ {
+ var sql = "CREATE TABLE IF NOT EXISTS store (key TEXT PRIMARY KEY,value TEXT)";
+ _this.db.run(sql,callback);
+ }
+ ],callback);
+}
+
+exports.database.prototype.get = function (key, callback)
+{
+ this.db.get("SELECT value FROM store WHERE key = ?", key, function(err,row)
+ {
+ callback(err,row ? row.value : null);
+ });
+}
+
+exports.database.prototype.set = function (key, value, callback)
+{
+ this.db.run("REPLACE INTO store VALUES (?,?)", key, value, callback);
+}
+
+exports.database.prototype.remove = function (key, callback)
+{
+ this.db.run("DELETE FROM store WHERE key = ?", key, callback);
+}
+
+exports.database.prototype.doBulk = function (bulk, callback)
+{
+ var sql = "BEGIN TRANSACTION;\n";
+ for(var i in bulk)
+ {
+ if(bulk[i].type == "set")
+ {
+ sql+="REPLACE INTO store VALUES (" + escape(bulk[i].key) + ", " + escape(bulk[i].value) + ");\n";
+ }
+ else if(bulk[i].type == "remove")
+ {
+ sql+="DELETE FROM store WHERE key = " + escape(bulk[i].key) + ";\n";
+ }
+ }
+ sql += "END TRANSACTION;";
+
+ this.db.exec(sql, function(err){
+ if(err)
+ {
+ console.error("ERROR WITH SQL: ");
+ console.error(sql);
+ }
+
+ callback(err);
+ });
+}
+
+exports.database.prototype.close = function(callback)
+{
+ this.db.close();
+ callback(null)
+}
+
+function escape (val)
+{
+ return "'"+val.replace("'", "\'")+"'";
+};
81 ueberDB.js
@@ -0,0 +1,81 @@
+/**
+ * 2011 Peter 'Pita' Martischka
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS-IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var dbWrapper = require("./dbWrapper");
+var async = require("async");
+
+/**
+ The Constructor
+*/
+exports.database = function(type, dbSettings, wrapperSettings)
+{
+ if(!type)
+ {
+ type = "sqlite3";
+ dbSettings = null;
+ wrapperSettings = null;
+ }
+
+ //saves all settings and require the db module
+ this.type = type;
+ this.db_module = require("./" + type + "_db");
+ this.dbSettings = dbSettings;
+ this.wrapperSettings = wrapperSettings;
+}
+
+exports.database.prototype.init = function(callback)
+{
+ var _this = this;
+
+ async.waterfall([
+ //initalizie the db driver
+ function(callback)
+ {
+ _this.db = new _this.db_module.database(_this.dbSettings);
+ _this.db.init(callback);
+ },
+ //initalize the db wrapper
+ function(callback)
+ {
+ _this.db = new dbWrapper.database(_this.db, _this.wrapperSettings);
+ _this.db.init(callback);
+ }
+ ],callback);
+}
+
+/**
+ Wrapper functions
+*/
+
+exports.database.prototype.get = function (key, callback)
+{
+ this.db.get(key, callback);
+}
+
+exports.database.prototype.set = function (key, value, callback)
+{
+ this.db.set(key, value, callback);
+}
+
+exports.database.prototype.remove = function (key, callback)
+{
+ this.db.remove(key, callback);
+}
+
+exports.database.prototype.close = function(callback)
+{
+ this.db.close(callback);
+}
0  var/.placeholder
No changes.
Please sign in to comment.
Something went wrong with that request. Please try again.