I am creating this Migration JS script using Node JS. Below is the full code of this migrate.js file.
const mysql = require("mysql");
var con = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
});
// Create Connection
con.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('MySQL connected as id ' + con.threadId);
});
// Create Database
const db_name = 'nuxt_mysql';
con.query("CREATE DATABASE IF NOT EXISTS " + db_name, function (err, result) {
if (err) throw err;
console.log(`Database "${db_name}" created.`);
// Select db
con.changeUser({database : db_name}, function(err) {
if (err) throw err;
console.log(`Database "${db_name}" selected.`);
// Create Tables
createTables();
});
});
// Create Tables
function createTables(){
createArticlesTable();
createUsersTable();
// Close Connection after tables are created
con.end();
console.log('MySQL connection closed.');
}
// Create Articles Table
function createArticlesTable(){
let sql = `CREATE TABLE IF NOT EXISTS articles (
id INT AUTO_INCREMENT NOT NULL,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
body TEXT NOT NULL,
date_added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
date_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
)`;
con.query(sql, function (err, result) {
if (err) throw err;
console.log(`Table "articles" created.`);
});
}
// Create Users Table
function createUsersTable(){
let sql = `CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT NOT NULL,
full_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
date_added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
date_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY (email)
)`;
con.query(sql, function (err, result) {
if (err) throw err;
console.log(`Table "users" created.`);
});
}
This script create a database first. Then it selects this db and then creates tables under it using different functions created for every table.
When I run node migrate.js , this is the output.
MySQL connected as id 257
Database "nuxt_mysql" created.
Database "nuxt_mysql" selected.
MySQL connection closed.
Table "articles" created.
Table "users" created.
Now the problem is, I want to close the mysql connection after all the tables have been created. And I think I will have to add async function somewhere. I am not very good with async/await so decided to post it.