Datase Migrations
Database migrations are executed using golang-migrate CLI
To install on MacOS
brew install golang-migrate
Creating a new migration
To create a new migration, run the following command with the name of the migration you want to create.
migrate create -ext sql -dir ./build/migrations create_results_table
This will create both an _up
and _down
migration. If these are empty, then a migration will fail, so ensure they are not committed if empty.
Run Migration to Local Database
To run a migration against a local datanase
make migrate-local-up
Fixing Dirty Migrations
error: Dirty database version 20220129043912. Fix and force version.
Grab the previous version from the migration before 20220129043912
and run the following command:
migrate --source file:// -database "postgres://postgres:postgres\!@127.0.0.1:5432/postgres?sslmode=disable" force $PREVIOUS_VERSION
Datase Seeding
In the event you need the dataqbase to be prepopulated with data, there is a server seed
entrypoint that can be invoked.
Seeding Local Database
To seed your local database, you can run the following command:
make seed
This will invoke the Seed.go
subcommand where you can put logic with the data you want to seed.
Below is an example of the Run()
command from Seed.go
func (d dbSeeder) Run(opts Options) error {
for i := 0; i < opts.Total; i++ {
name := generateName()
description := generateDesc()
id := generateRandomNumber()
sql := fmt.Sprintf("INSERT INTO template (name, description, id) VALUES ('%s', '%s','%d')", name, description, id)
_, err := d.db.Db.Exec(sql)
if err != nil {
...
}
...
}
...
}
Seeding Production Dataase
While it is possible to use the same method for seeding that is done locally, it is advised to use a database migration if possible for seeding production.
If a database migration does not work, then reach out in #product-platform-delivery
for help to get this setup.