Last active
March 11, 2019 22:16
-
-
Save deeperton/640400e8517ec017ea72f41c95ad3dc7 to your computer and use it in GitHub Desktop.
A very simple snippet for web-tools to run queries against sql.js database stored in localStorage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(DBName) { | |
var raw_DB = localStorage.getItem(DBName); | |
if (raw_DB) { | |
window._db = (function(raw) { | |
let db = new SQL.Database(JSON.parse(raw)); | |
return { | |
run: function(sql) { | |
let data = db.exec(sql); | |
if (data.length == 0) { | |
console.log('SQL returns empty result'); | |
return; | |
} | |
let cols = data[0].columns; | |
let result = data[0].values.map((row) => { | |
let res = {}; | |
cols.forEach( (col, i) => { | |
res[col] = row[i] | |
}); | |
return res; | |
}); | |
console.table(result); | |
}, | |
tables: function() { | |
this.run('SELECT name FROM sqlite_master WHERE type="table" ORDER BY name;'); | |
}, | |
columns: function(tableName) { | |
this.run(`pragma table_info("${tableName}")`); | |
}, | |
view: function(tableName, max = 0) { | |
this.run(`SELECT * FROM ${tableName}` + (max > 0 ? ` LIMIT ${max}`: '')); | |
} | |
}; | |
})(raw_DB); | |
} | |
})('{{DB_NAME}}'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment