This blog outlines the process of creating a custom database migration system using Node.js, & any database ORM. Furthermore, it explains creating migration files, writing migration code, and applying Electron-specific changes in order for the migration system to operate effectively in a production environment.
In this blog, we demonstrate the procedure for developing a tailor-made migration system utilizing Node.js and any database Object-Relational Mapping (ORM). The blog consists of a directory named "migrations" to store all necessary migration files, which contain both up and down queries. Furthermore, we explain the adjustments needed specifically for Electron in order to operate the migration system effectively in a production environment.
Before we start writing our own migration system code, first create a folder named migrations in root directory to store all migration files, and inside that add migration file like this:
Migration Folder
Create migration file in the following format:
| (migration id).(migration name).sql
Inside each migration file (sample.sql) add migration queries in this format
Each migration contains up and down queries
Now Let’s write our custom migration. We are using better-sqlite3 for managing database in electron app.Also I’ll be using typescript for all our code
Create a function dbMigrate and add the following code
After this we will read content from each migration file
Now we have read the content from migration files we will grab the up and down queries
After this we will get the list of already applied migrations.Here I’m using better sqlite-3 query methods
Now we will apply our pending migrations.I’m running these migration in transaction so that if any error occurs our database remains safe
Hurray! We have successfully applied our migrations.
But wait what about reverting any migration, for that we will have to run our down query Whenever you want to rollback or revert your migration run the following code
The above code also undo migrations that exist only in the database but not in files.
Finally, we have created our custom migration system from scratch. You can easily use this migration system to any nodejs application with any other database orm.
Now we will talk about electron specific changes to properly run this migration in production.
If you run the above migration code in development it will run successfully without any problem. But when you package or build your app, your app crashes and you will get an exception error of migration path not found. To solve this issue we have to copy our migration folder in the packaged app.
We are using electron builder to package our app, to copy our migration folder in packaged app just add this line in electron builder config