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
- 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
- Atlas installed on your machine:
- macOS + Linux
- Homebrew
- Docker
- Windows
- Manual Installation
To download and install the latest release of the Atlas CLI, simply run the following in your terminal:
curl -sSf https://atlasgo.sh | sh
Get the latest release with Homebrew:
brew install ariga/tap/atlas
To pull the Atlas image and run it as a Docker container:
docker pull arigaio/atlas
docker run --rm arigaio/atlas --help
If the container needs access to the host network or a local directory, use the --net=host
flag and mount the desired
directory:
docker run --rm --net=host \
-v $(pwd)/migrations:/migrations \
arigaio/atlas migrate apply
--url "mysql://root:pass@:3306/test"
Download the latest release and move the atlas binary to a file location on your system PATH.
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 containgorm
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 containgorm
struct tags, you can use the provider as a library in your Go program to load your GORM schema into Atlas.