Created
January 11, 2019 01:08
-
-
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).
This file contains 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
/* 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