Autostrada
Autostrada
Create a new codebase Get Autostrada Plus
Documentation Changelog Roadmap Give feedback
Login

DocumentationJSON API › SQL migrations

SQL migrations

If you select the option to include helpers for managing SQL migrations when generating your codebase, the admin makefile in the will contain the following commands for you to run:

Command Description
$ make migrations/new name=add_example_table Create a new database migration in the assets/migrations folder.
$ make migrations/up Apply all up migrations.
$ make migrations/down Apply all down migrations.
$ make migrations/goto version=N Migrate up or down to a specific migration (where N is the migration version number).
$ make migrations/force version=N Force the database to a specific version without running migrations.
$ make migrations/version Display the currently in-use migration version.

Hint: You can run make help at any time for a reminder of these commands.

Under the hood, these Makefile commands use the golang-migrate/migrate tool to manage migrations. Feel free to edit the commands if you need to.

If you are using PostgreSQL or MySQL, you will need to set a DB_DSN environment variable containing your database connection string for the Makefile migration commands to use.

# For PostgreSQL
$ export DB_DSN="user:pass@localhost:port/db"

# For MySQL
$ export DB_DSN="user:pass@protocol(host:port)/db?parseTime=true"
Working with migrations

Each migration consists of a pair of files: an up migration and a corresponding down migration.

The up migration applies a change to your database schema (for example, creating a table or adding a column), while the down migration reverses that change.

A typical workflow looks like this:

Migrations are applied in order, based on their version number, and tracked in the database schema_migrations table.

Running up migrations on startup

When you build or run the application, the migration files in the assets/migrations directory are embedded into the application binary.

The internal/database package provides a MigrateUp() function which runs all embedded up migrations. By default, this runs automatically on application startup.

If you don't want migrations to run automatically, you can disable this via the configuration settings.

If you're using command-line flags for configuration, pass --db-automigrate=false when starting the application. For example:

$ go run ./cmd/api --db-automigrate=false

If you're using environment variables, set DB_AUTOMIGRATE=false.

$ export DB_AUTOMIGRATE=false