reviewer's feedback: SQLite: now using static strings + bound parameters

This commit is contained in:
gorhill 2015-05-27 15:31:36 -04:00
parent 56ac5a1105
commit 53fc1063f9
1 changed files with 137 additions and 116 deletions

View File

@ -93,51 +93,53 @@ window.addEventListener('unload', function() {
/******************************************************************************/ /******************************************************************************/
var SQLite = { // API matches that of chrome.storage.local:
open: function() { // https://developer.chrome.com/extensions/storage
vAPI.storage = (function() {
var db = null;
var close = function() {
if ( db === null ) {
return;
}
db.createStatement('VACUUM').executeAsync();
db.asyncClose();
db = null;
};
var open = function() {
if ( db !== null ) {
return;
}
// Create path
var path = Services.dirsvc.get('ProfD', Ci.nsIFile); var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
path.append('extension-data'); path.append('extension-data');
if ( !path.exists() ) { if ( !path.exists() ) {
path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8)); path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
} }
if ( !path.isDirectory() ) { if ( !path.isDirectory() ) {
throw Error('Should be a directory...'); throw Error('Should be a directory...');
} }
path.append(location.host + '.sqlite'); path.append(location.host + '.sqlite');
this.db = Services.storage.openDatabase(path);
this.db.executeSimpleSQL(
'CREATE TABLE IF NOT EXISTS settings' +
'(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
);
cleanupTasks.push(function() { // Open database
// VACUUM somewhere else, instead on unload? db = Services.storage.openDatabase(path);
SQLite.run('VACUUM');
SQLite.db.asyncClose();
});
},
run: function(query, values, callback) { // Database was opened, register cleanup task
if ( !this.db ) { cleanupTasks.push(close);
this.open();
}
// Setup database
db.createAsyncStatement('CREATE TABLE IF NOT EXISTS settings(name TEXT PRIMARY KEY NOT NULL, value TEXT);')
.executeAsync();
};
// Execute a query
var runStatement = function(stmt, callback) {
var result = {}; var result = {};
query = this.db.createAsyncStatement(query); stmt.executeAsync({
if ( Array.isArray(values) && values.length ) {
var i = values.length;
while ( i-- ) {
query.bindByIndex(i, values[i]);
}
}
query.executeAsync({
handleResult: function(rows) { handleResult: function(rows) {
if ( !rows || typeof callback !== 'function' ) { if ( !rows || typeof callback !== 'function' ) {
return; return;
@ -160,120 +162,139 @@ var SQLite = {
console.error('SQLite error ', error.result, error.message); console.error('SQLite error ', error.result, error.message);
} }
}); });
};
var bindNames = function(stmt, names) {
if ( Array.isArray(names) === false || names.length === 0 ) {
return;
} }
}; var params = stmt.newBindingParamsArray();
var i = names.length, bp;
/******************************************************************************/ while ( i-- ) {
bp = params.newBindingParams();
vAPI.storage = { bp.bindByName('name', names[i]);
QUOTA_BYTES: 100 * 1024 * 1024, params.addParams(bp);
sqlWhere: function(col, params) {
if ( params > 0 ) {
params = new Array(params + 1).join('?, ').slice(0, -2);
return ' WHERE ' + col + ' IN (' + params + ')';
} }
stmt.bindParameters(params);
};
return ''; var clear = function(callback) {
}, if ( db === null ) {
open();
}
runStatement(db.createStatement('DELETE FROM settings; VACUUM;'), callback);
};
get: function(details, callback) { var getBytesInUse = function(keys, callback) {
if ( typeof callback !== 'function' ) { if ( typeof callback !== 'function' ) {
return; return;
} }
var values = [], defaults = false; if ( db === null ) {
open();
}
var stmt;
if ( Array.isArray(keys) ) {
stmt = db.createStatement('SELECT "size" AS size, SUM(LENGTH(value)) FROM settings WHERE name = :name');
bindNames(keys);
} else {
stmt = db.createStatement('SELECT "size" AS size, SUM(LENGTH(value)) FROM settings');
}
runStatement(stmt, function(result) {
callback(result.size);
});
};
var read = function(details, callback) {
if ( typeof callback !== 'function' ) {
return;
}
if ( db === null ) {
open();
}
var names = [];
if ( details !== null ) { if ( details !== null ) {
if ( Array.isArray(details) ) { if ( Array.isArray(details) ) {
values = details; names = details;
} else if ( typeof details === 'object' ) { } else if ( typeof details === 'object' ) {
defaults = true; names = Object.keys(details);
values = Object.keys(details);
} else { } else {
values = [details.toString()]; names = [details.toString()];
} }
} }
SQLite.run( var stmt;
'SELECT * FROM settings' + this.sqlWhere('name', values.length), if ( names.length === 0 ) {
values, stmt = db.createStatement('SELECT * FROM settings');
function(result) { } else {
stmt = db.createStatement('SELECT * FROM settings WHERE name = :name');
bindNames(stmt, names);
}
runStatement(stmt, function(result) {
var key; var key;
for ( key in result ) { for ( key in result ) {
result[key] = JSON.parse(result[key]); result[key] = JSON.parse(result[key]);
} }
if ( typeof details === 'object' && details !== null ) {
if ( defaults ) {
for ( key in details ) { for ( key in details ) {
if ( result[key] === undefined ) { if ( result.hasOwnProperty(key) === false ) {
result[key] = details[key]; result[key] = details[key];
} }
} }
} }
callback(result); callback(result);
});
};
var remove = function(keys, callback) {
if ( db === null ) {
open();
} }
); var stmt = db.createStatement('DELETE FROM settings WHERE name = :name');
}, bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
runStatement(stmt, callback);
};
set: function(details, callback) { var write = function(details, callback) {
var key, values = [], placeholders = []; if ( db === null ) {
open();
}
for ( key in details ) { var stmt = db.createStatement('INSERT OR REPLACE INTO settings (name, value) VALUES(:name, :value)');
if ( !details.hasOwnProperty(key) ) { var params = stmt.newBindingParamsArray(), bp;
for ( var key in details ) {
if ( details.hasOwnProperty(key) === false ) {
continue; continue;
} }
values.push(key); bp = params.newBindingParams();
values.push(JSON.stringify(details[key])); bp.bindByName('name', key);
placeholders.push('?, ?'); bp.bindByName('value', JSON.stringify(details[key]));
params.addParams(bp);
} }
if ( params.length === 0 ) {
if ( !values.length ) {
return; return;
} }
SQLite.run( stmt.bindParameters(params);
'INSERT OR REPLACE INTO settings (name, value) SELECT ' + runStatement(stmt, callback);
placeholders.join(' UNION SELECT '), };
values,
callback
);
},
remove: function(keys, callback) { // Export API
if ( typeof keys === 'string' ) { var api = {
keys = [keys]; QUOTA_BYTES: 100 * 1024 * 1024,
} clear: clear,
get: read,
SQLite.run( getBytesInUse: getBytesInUse,
'DELETE FROM settings' + this.sqlWhere('name', keys.length), remove: remove,
keys, set: write
callback };
); return api;
}, })();
clear: function(callback) {
SQLite.run('DELETE FROM settings');
SQLite.run('VACUUM', null, callback);
},
getBytesInUse: function(keys, callback) {
if ( typeof callback !== 'function' ) {
return;
}
SQLite.run(
'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
keys,
function(result) {
callback(result.size);
}
);
}
};
/******************************************************************************/ /******************************************************************************/