Skip to content

Instantly share code, notes, and snippets.

@scorredoira
Last active August 4, 2018 10:03
Show Gist options
  • Save scorredoira/5d5d366aaf5223a14100e0db22efa415 to your computer and use it in GitHub Desktop.
Save scorredoira/5d5d366aaf5223a14100e0db22efa415 to your computer and use it in GitHub Desktop.
import "stdlib/native"
import * as cli from "stdlib/cmdline"
/**
* ------------------------------------------------------------------
* Extract databases and tables from dump files
*
* usage: amura extract -f foo.sql -d bardb
* ------------------------------------------------------------------
*/
function main(...args: string[]) {
let p = cli.newParser()
cli.addFlag(p, "f", "file")
cli.addFlag(p, "d", "database")
cli.addFlag(p, "t", "table")
cli.addOption(p, "u", "uncompress")
cli.parse(p, args)
let file = cli.flag(p, "file")
let database = cli.flag(p, "database")
let table = cli.flag(p, "table")
let uncompress = cli.option(p, "uncompress")
let cmd = "";
if (uncompress) {
cmd += "bzip2 -cd " + file + " | sed -n \"/^-- Current Database: \`" + database + "\`/,/^-- Current Database: \`/p\" "
} else {
cmd += "sed -n \"/^-- Current Database: \`" + database + "\`/,/^-- Current Database: \`/p\" " + file;
}
if (table) {
cmd += " | sed -n '/^CREATE TABLE " + table + "`/,/^DROP TABLE /p' "
}
cmd += " > tmp.sql"
let fs = os.fileSystem;
// disable constraints
fs.write("out.sql", `
SET @BACKUP_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS;
SET @@FOREIGN_KEY_CHECKS=0;
`)
let out = os.exec("bash", "-c", cmd)
if (out) {
fmt.println(out)
}
out = os.exec("bash", "-c", "cat tmp.sql >> out.sql")
if (out) {
fmt.println(out)
}
// enable constraints
fs.append("out.sql", `
SET @@FOREIGN_KEY_CHECKS=@BACKUP_FOREIGN_KEY_CHECKS
`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment