Created
May 10, 2022 07:17
-
-
Save drikusroor/5e7e3c7ef859702798ab390cbfef1fe4 to your computer and use it in GitHub Desktop.
Easy node.js mysql database table seeder
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
// first, install npm dependencies: | |
// npm i mysql2 @faker-js/faker dotenv | |
// and don't forget to add the mysql db credentials to your .env file | |
// run with the command "node ./index.js" | |
const mysql = require("mysql2"); | |
const { faker } = require("@faker-js/faker"); | |
require("dotenv").config(); | |
function getSeedQuery(amount = 10000) { | |
return Array.from({ length: amount }) | |
.map(() => { | |
const date = faker.date.past(5); | |
const time = new Date(); | |
const currency = faker.finance.currencyCode(); | |
const rate = faker.finance.amount(1.0, 9.99).toString(); | |
const sql = `INSERT INTO ExchangeRates (date, time, currency, rate) VALUES ('${date.toISOString()}', '${time.toTimeString()}', '${currency}', '${rate}')`; | |
return sql; | |
}) | |
.join(";\n"); | |
} | |
const connection = mysql.createConnection({ | |
host: process.env.DB_HOST, | |
user: process.env.DB_USER, | |
password: process.env.DB_PASS, | |
database: process.env.DB_NAME, | |
multipleStatements: true, | |
}); | |
connection.connect(); | |
const seedQuery = getSeedQuery(10000); | |
connection.query(seedQuery, (err, results) => { | |
if (err) { | |
console.log(err); | |
} | |
console.log("Seeding complete"); | |
connection.end(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment