2015-07-22 00:58:34 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/*global Promise*/
|
|
|
|
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();
|
|
|
|
}
|
|
|
|
|
2015-07-23 02:58:18 +00:00
|
|
|
if (!dbs[opts.filename] || dbs[opts.filename].__key !== opts.key) {
|
|
|
|
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.__key = opts.key;
|
|
|
|
|
|
|
|
return new Promise(function (resolve, reject) {
|
|
|
|
db.serialize(function() {
|
|
|
|
var setup = [];
|
|
|
|
|
|
|
|
if (opts.key) {
|
|
|
|
// TODO test key length
|
|
|
|
if (!opts.bits) {
|
|
|
|
opts.bits = 128;
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO db.run(sql, function () { resolve() });
|
|
|
|
setup.push(new Promise(function (resolve, reject) {
|
|
|
|
db.run("PRAGMA KEY = \"x'" + sanitize(opts.key) + "'\"", [], function (err) {
|
|
|
|
if (err) { reject(err); return; }
|
|
|
|
resolve(this);
|
|
|
|
});
|
|
|
|
}));
|
|
|
|
setup.push(new Promise(function (resolve, reject) {
|
|
|
|
db.run("PRAGMA CIPHER = 'aes-" + sanitize(opts.bits) + "-cbc'", [], function (err) {
|
|
|
|
if (err) { reject(err); return; }
|
|
|
|
resolve(this);
|
|
|
|
});
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
Promise.all(setup).then(function () { resolve(db); }, reject);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
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;
|