sqlite3-cluster.js/wrapper.js

99 lines
2.1 KiB
JavaScript
Raw Normal View History

2015-07-22 00:58:34 +00:00
'use strict';
/*global Promise*/
2015-07-31 21:06:29 +00:00
var PromiseA = Promise;
try {
PromiseA = require('bluebird').Promise;
} catch(e) {
console.warn("For better Promise support please use bluebird");
}
2015-07-22 00:58:34 +00:00
var sqlite3 = require('sqlite3');
var dbs = {};
function sanitize(str) {
return String(str).replace("'", "''");
}
function create(opts) {
var db;
if (!opts) {
opts = {};
}
if (opts.verbose) {
sqlite3.verbose();
}
if (!dbs[opts.filename]) {
2015-07-23 02:58:18 +00:00
dbs[opts.filename] = new sqlite3.Database(opts.filename);
2015-07-22 00:58:34 +00:00
}
2015-07-23 02:58:18 +00:00
db = dbs[opts.filename];
db.sanitize = sanitize;
2015-07-24 20:47:11 +00:00
db.escape = sanitize;
2015-07-22 00:58:34 +00:00
db.init = function (newOpts) {
if (!newOpts) {
newOpts = {};
}
2015-07-22 00:58:34 +00:00
var key = newOpts.key || opts.key;
var bits = newOpts.bits || opts.bits;
2015-07-31 21:06:29 +00:00
return new PromiseA(function (resolve, reject) {
if (db._initialized) {
resolve(db);
return;
}
if (!key) {
if (!bits) {
db._initialized = true;
}
resolve(db);
return;
}
// TODO test key length
db._initialized = true;
db.serialize(function () {
var setup = [];
if (!bits) {
bits = 128;
2015-07-22 00:58:34 +00:00
}
// TODO db.run(sql, function () { resolve() });
2015-07-31 21:06:29 +00:00
setup.push(new PromiseA(function (resolve, reject) {
db.run("PRAGMA KEY = \"x'" + sanitize(key) + "'\"", [], function (err) {
2015-07-22 00:58:34 +00:00
if (err) { reject(err); return; }
resolve(this);
});
}));
2015-07-31 21:06:29 +00:00
setup.push(new PromiseA(function (resolve, reject) {
//process.nextTick(function () {
db.run("PRAGMA CIPHER = 'aes-" + sanitize(bits) + "-cbc'", [], function (err) {
2015-07-22 00:58:34 +00:00
if (err) { reject(err); return; }
resolve(this);
});
//});
2015-07-22 00:58:34 +00:00
}));
2015-07-31 21:06:29 +00:00
PromiseA.all(setup).then(function () {
// restore original functions
resolve(db);
}, reject);
});
2015-07-22 00:58:34 +00:00
});
};
return db.init(opts);
2015-07-22 00:58:34 +00:00
}
module.exports.sanitize = sanitize;
2015-07-24 20:47:11 +00:00
module.exports.escape = sanitize;
2015-07-22 00:58:34 +00:00
module.exports.Database = sqlite3.Database;
module.exports.create = create;