Migrations
Last updated
Was this helpful?
Last updated
Was this helpful?
This guide walks you through migrating a database using an Express app and a MySQL Capsule.
You might find our and our helpful.
To install db-migrate
, first clone your GitHub repository with the following command (make sure to replace the username and repository name with your own):
git clone https://github.com/git_username/repository_name.git
db-migrate
To use migration commands, install both db-migrate
and db-migrate-mysql
with the following commands:
npm install -g db-migratenpm i db-migrate-mysql
database.json
The db-migrate
package connects to a database through a database.json
file.
Create a file called database.json
in your root directory and populate it with your database information. The example below shows how to connect to both a local database called "dev"
and a MySQL Data Capsule called "prod"
(be sure to replace the database information with your own):
Here we also add"sql-file": true
to ensure that database migrations run using SQL files, which we'll create in the next step.
Find the database URL for a MySQL Data Capsule in the Config tab of a Backend Capsule:
You can also access the database URL using an environment variable as follows:
"prod": {"ENV":"DATABASE_URL"},
Run the following command to create a folder to store migrations:
db-migrate create insert_unique_name --sql-file
The folder should contain three files:
MySQL queries are stored in the two generated SQL files: One named with an up
suffix and the other with a down
suffix.
Insert the following SQL query into the down
file to remove a row from the database:
Insert the following SQL query into the up
file to insert a row into the database:
Add your own MySQL queries to these SQL files to define custom database migrations.
In the root directory of the project, update the "scripts"
section in the package.json
file as follows:
Modify these scripts to suit your developer and production environments.
The migration scripts shown here are designed to be used on Code Capsules or in a developer environment.
To run these migrations in a production environment, update the Capsule's Run Command to execute the migration scripts.
Edit the Run Command in the Config tab of the Backend Capsule.
Finally, commit and push your changes to your GitHub repository to update the codebase and trigger the migrations.
View migration activity in the Backend Capsule's Logs tab. The output will look similar to this: