I want to create a database and some tables with node.js. The Problem is, that the tables are created at the same time and sometimes(!) some tables are not created, because they don't exist at the creation of the referencing table. Yes, usually I am executing the sql statements one after the other so if I execute this in my mysql workbench, there is no error. But in node because of the asynchronous event loop (if I understood this right) it will be executed at the same time.
Here is some of my code:
const pool = require("./database2"); // using the pool connection of mysql2
const executeOne = (sql) => {
pool.execute(sql, (err, result) => {
if (err) console.log(err);
})
}
client.on("guildCreate", (guild) => {
guildname = guild.name.replace(" ", "_");
const createTables = new Promise((resolve, reject) => {
executeOne(`CREATE DATABASE IF NOT EXISTS ${guildname}`);
//tried to set the checks off but doesn't work either
executeOne(`SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS;`);
executeOne(`SET FOREIGN_KEY_CHECKS=0;`);
resolve()
})
createTables.then(() => {
executeOne("1st stmt"); //no foreign keys
})
.then(() => {
executeOne("2nd stmt"); //no fks
})
.then(() => {
executeOne("3rd stmt"); //1 fk referencing 1st stmt
})
.then(() => {
executeOne("4th stmt"); //no fks
})
.then(() => {
executeOne("5th stmt"); //2fks, one ref. 2nd stmt, one ref. 3rd stmt
})
.then(() => {
executeOne("6th stmt"); //2fks, one ref. 3rd stmt, one ref. 4th stmt
})
.catch((err) => {
console.log(err)
});
})
So I basically don't understand how to executing the statements one after another, or are they other methods to do this?
Thanks for help!