Skip to content

Instantly share code, notes, and snippets.

@sbrichardson
Created January 11, 2019 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbrichardson/6df39a99b748b7957a3b983b344ee537 to your computer and use it in GitHub Desktop.
Save sbrichardson/6df39a99b748b7957a3b983b344ee537 to your computer and use it in GitHub Desktop.
Browser based sqlite -> JSON/CSV. Exports sqlite database tables (using sql.js) to JSON, CSV, other (dev in progress).
/* NOTE Originally based on github.com/Philzen/WebSql-Loader */
const TABLE_SQL = "SELECT tbl_name from sqlite_master WHERE type = 'table'"
const MASTER_SQL = 'SELECT sql FROM sqlite_master'
const WEBKIT_INFO = '__WebKitDatabaseInfoTable__'
/* TODO Add other formats */
const FORMAT = {
JSON: 'json',
// CSV: 'csv',
// SQL: 'sql',
}
const DEFAULT_OPTS = {
format: FORMAT.JSON,
schema: true,
}
/**
* @param db {Database} SQLite db instance
* @param opts {Object} Options
*/
class Exporter {
constructor(db, opts) {
this.db = db
this.opts = {
...DEFAULT_OPTS,
...(opts || {}),
}
}
/* TODO Add other formats */
formatExportedData = (data, format) => {
if (format === FORMAT.JSON) return data
switch (format) {
default:
return data
}
}
/* Get SQL statements to CREATE all tables in db */
getSchema = () => {
const [{ values: rows } = {}] = this.db.exec(MASTER_SQL)
return rows.map(row => row[0]).filter(x => x !== null)
}
/* Get names of all tables in the Database */
getTables = () => {
const [{ values: rows } = {}] = this.db.exec(TABLE_SQL)
return rows.map(row => row[0]).filter(x => x !== WEBKIT_INFO)
}
/* TODO Verify table name is string/escaped, no spaces, exists */
exportTable = tableName => {
const stmt = `SELECT * from ${tableName};`
const [{ columns, values } = {}] = this.db.exec(stmt)
return {
...this.formatExportedData({
columns: [...(columns || [])],
data: [...(values || [])],
}),
tableName,
}
}
exportAllTables = () => {
return this.getTables().reduce((acc, x, i) => {
acc[x] = this.exportTable(x)
return acc
}, {})
}
}
export default Exporter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment