Last active
May 31, 2021 06:02
-
-
Save wiedymi/066617d3ea6c3479dfbb8fb4476338e6 to your computer and use it in GitHub Desktop.
Dump mysql database (json)
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
require('dotenv').config() | |
const { promisify } = require('util') | |
const mysql = require('mysql'); | |
const fs = require('fs'); | |
const db = { | |
database: process.env.DATABASE, | |
host: process.env.DB_HOST, | |
user: process.env.DB_USER, | |
password: process.env.DB_PASS, | |
} | |
if (!db.database) { | |
return console.log('No DATABASE provided') | |
} | |
if (!db.host) { | |
return console.log('No DB_HOST provided') | |
} | |
if (!db.user) { | |
return console.log('No DB_USER provided') | |
} | |
if (!db.password) { | |
return console.log('No DB_PASS provided') | |
} | |
const client = mysql.createConnection({ | |
host: db.host, | |
user: db.user, | |
password: db.password, | |
}); | |
client.asyncQuery = promisify(client.query) | |
const dumpTable = async (tableName) => { | |
const fileName = `./backup/${tableName}.json` | |
const results = await client.asyncQuery(`select * from ${db.database}.${tableName};`) | |
await fs.promises.writeFile(fileName, JSON.stringify(results)) | |
console.log(`${tableName} - done!`); | |
} | |
async function main() { | |
console.log('Getting all table names to backup...') | |
const tables = await client.asyncQuery(`SELECT table_name FROM information_schema.tables | |
WHERE table_schema = '${db.database}'`) | |
console.log('Clearing backup folder...') | |
await fs.promises.rmdir('./backup', { recursive: true }); | |
await fs.promises.mkdir('./backup', { recursive: true }); | |
console.log('Downloading tables...') | |
const tableNames = tables.map(({ table_name }) => table_name) | |
for (const tableName of tableNames) { | |
await dumpTable(tableName) | |
} | |
console.log('Closing connection...') | |
client.end(); | |
} | |
try { | |
main() | |
} catch (error) { | |
console.log('Something went wrong', error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment