Skip to main content

Automatic Schema Migration Planning for GORM

GORM allows users to manage their database schemas using its AutoMigrate feature, which is usually sufficient during development and in many simple cases. However, many teams eventually need more control and decide to employ the versioned migrations methodology.

Once this happens, the responsibility of planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers.

Atlas can help in these cases by automatically planning database schema migrations for developers using GORM by calculating the diff between the current state of the database, and its desired state defined by GORM models.

To use Atlas with GORM, users can utilize the GORM Atlas Provider, a small Go program that can load the schema of a GORM project into Atlas.

Prerequisites

  1. A local GORM project

If you don't have a GORM project handy, you can use go-admin-team/go-admin as a starting point:

git clone git@github.com:go-admin-team/go-admin.git
  1. Atlas installed on your machine:

To download and install the latest release of the Atlas CLI, simply run the following in your terminal:

curl -sSf https://atlasgo.sh | sh
  1. The GORM Atlas Provider

Install the provider by running:

go get -u ariga.io/atlas-provider-gorm

Standalone vs Go Program mode

The Atlas GORM Provider can be used in two modes:

  • Standalone - If all of your GORM models exist in a single package and either embed gorm.Model or contain gorm struct tags, you can use the provider directly to load your GORM schema into Atlas.
  • Go Program - If your GORM models are spread across multiple packages, or do not embed gorm.Model or contain gorm struct tags, you can use the provider as a library in your Go program to load your GORM schema into Atlas.