While working with SQL databases and especially when the application is in the production stage. migration helps to change the current state of the database to another state, and vice versa like Github version control.
Let's start with all the useful commands
There are some prerequisites to use migration in the project.
- You must have initiated the node project with the npm init command in your project directory.
- Install Sequelze npm package ```
npm i sequelize
In the latest version of sequelize we don't need sequelize-cli package. we can run migration commands by only installing sequelize package.
That is it, you are good to go.
## First command after Installing the npm package
bash
npx sequelize init
* This will initiate migration setup and create 4 directories in your project structure
1 config
2 migrations
3 models
4 seeders
![All Sequelize files](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ln34nigibowmy08b8pk.png)
* However we can create this setup for individual directories as well.
bash
npx sequelize init:config // Create config folder and config.json
npx sequelize init:migrations // Create Migration folder
npx sequelize init:seeders // Create seeders folder
npx sequelize init:models // Create a model folder and index.js to handle all the models
### Custom configuration
* We can change the path of all the folders according to the needs of our project structure.
* For that we first need to create ".sequelizerc" file in the root directory of the project and set up our configuration of Sequelize in the newly created file as below given example.
![custom sequelize configration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xsc9couojmw7z6yjwit7.png)
## Create migration files and run migrations
After setting up Sequelize in the project we create migration for our database models with given commands.
bash
// This will create the new migration file
npx sequelize migration:generate --name=creat-user
// Apply all the pending database migrations
npx sequelize db:migrate
// Apply migration of individual file
npx sequelize db:migrate --to 20230527090813-create-user.js
* Undo migrations
bash
// undo migration of specific migration file
npx sequelize db:migrate:undo --name
## Create seeder files and run seeders
bash
// Show the status of current seeder files
npx sequelize db:migrate:status
* create a seeder file
bash
// create seeder file
sequelize seed:generate --name=users
* Run seeder file
bash
// Run all the seeder files make sure you run only once
npx sequelize db:seed:all
// Run only spesefic seeder file
sequelize db:seed --seed 20230527092604-users.js
<hr>
### For more content check out my `Github š`
Top comments (0)