Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created December 13, 2016 04:02
Show Gist options
  • Save yowcow/14d9845005d115506fae13580cc39de1 to your computer and use it in GitHub Desktop.
Save yowcow/14d9845005d115506fae13580cc39de1 to your computer and use it in GitHub Desktop.
JavaScript fixture loading into MySQL
const queries = [
["SET FOREIGN_KEY_CHECKS=0", []],
["TRUNCATE TABLE foo", []],
["INSERT INTO foo (id, name) VALUES (?, ?)", [1, "foooo"]],
["TRUNCATE TABLE bar", []],
["INSERT INTO bar (id, name) VALUES (?, ?)", [2, "baaaar"]],
["SET FOREIGN_KEY_CHECKS=1", []]
]
const db = mysql.createConnection(...)
const executeQueries = (db, queries = [], callback) => {
if (!queries.length) return callback()
const p = new Promise((resolve, reject) => {
db.execute(
queries[0][0],
queries[0][1],
(err, res) => err ? reject(err) : resolve(res)
)
})
p.then(res => executeQueries(db, queries.splice(1), callback))
p.catch(err => { throw err })
}
executeQueries(db, queries, () => db.close())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment