Multiple Schema Migrations
Using the Atlas migration engine, an Ent schema can be defined and managed across multiple database schemas. This guides show how to achieve this with three simple steps:
ATLAS LOGIN REQUIRED
atlas login
Install Atlas
To install the latest release of Atlas, simply run one of the following commands in your terminal, or check out the Atlas website:
- macOS + Linux
- Homebrew
- Docker
- Windows
curl -sSf https://atlasgo.sh | sh
brew install ariga/tap/atlas
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.
Login to Atlas
$ atlas login a8m
You are now connected to "a8m" on Atlas Cloud.
Annotate your Ent schemas
The entsql
package allows annotating an Ent schema with a database schema name. For example:
// Annotations of the User.
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db3"),
}
}
To share the same schema configuration across multiple Ent schemas, you can either use ent.Mixin
or define and embed a base schema:
- Mixin schema
- Base schema
mixin.go
// Mixin holds the default configuration for most schemas in this package.
type Mixin struct {
mixin.Schema
}
// Annotations of the Mixin.
func (Mixin) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db1"),
}
}
user.go
// User holds the edge schema definition of the User entity.
type User struct {
ent.Schema
}
// Mixin defines the schemas that mixed into this schema.
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
Mixin{},
}
}
base.go
// base holds the default configuration for most schemas in this package.
type base struct {
ent.Schema
}
// Annotations of the base schema.
func (base) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db1"),
}
}
user.go
// User holds the edge schema definition of the User entity.
type User struct {
base
}
Generate migrations
To generate a migration, use the atlas migrate diff
command. For example:
- MySQL
- MariaDB
- PostgreSQL
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://mysql/8"
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://maria/8"
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://postgres/15/dev"
note
The migrate
diff command generates a list of SQL statements without indentation by default. If you would like to generate the SQL statements with indentation, use the --format
flag. For example:
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://postgres/15/dev" \
--format "{{ sql . \" \" }}"