npm migration package for mysql, mariadb
- Installation
- Setup
- Table Migration
- create migration
- code sample for table migration file
- run migration file
- up
- rollback
- Data Seeding
- create seeding
- code sample for data seeding file
- run seeding file
- up
- rollback
npm install mysql-migrator
create migrator.js with the following code.
const {mysqlMigrator} = require('mysql-migrator');
const dbConfig = {
host: 'your-database-host',
user: 'your-database-user-name',
port: 3306,
password: '******',
database: 'your-database-name'
}
const migrationsPath = __dirname+"/databases";
mysqlMigrator.init(dbConfig,migrationsPath);
node migrator.js migration create create_table_user
there are two function up and rollback functions.
- up is for upgrading
- rollback is for downgrading. to use this function when you need to roll back to previous batch.
//write sql statement to create or modify
module.exports = {
"up": `
CREATE TABLE IF NOT EXISTS User (
id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(45) NOT NULL,
password varchar(200) NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
deleted_at datetime DEFAULT NULL
);
`,
"rollback":`
DROP TABLE IF EXISTS User;
`
}
node migrator.js migration up
node migrator.js migration rollback
node migrator.js seeding create user_data_seeding
there are two function up and rollback functions.
- up is for upgrading
- rollback is for downgrading. to use this function when you need to roll back to previous batch.
//write sql statement to create or modify
module.exports = {
"up": `
INSERT INTO User VALUES(NULL,"AKN","xxxxxx","2/1/22","2/1/22",NULL);
`,
"rollback":`
TRUNCATE TABLE User;
`
}
or
//write sql statement to create or modify
module.exports = {
"up": async function(_callBack){
let query = `INSERT INTO User VALUES(NULL,"AKN","xxxxxx","2/1/22","2/1/22",NULL);`;
return await new Promise(async (resolve,reject)=>{
resolve( await _callBack(query));
}); ;
},
"rollback":function(){
let query = `TRUNCATE TABLE User;`;
return query;
}
}
node migrator.js seeding up
node migrator.js seeding rollback
Thank You for Visiting to my repo. :)