Migración Multi-esquema
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Usando el motor de migración de Atlas, un esquema Ent puede definirse y gestionarse en múltiples esquemas de base de datos. Esta guía muestra cómo lograrlo en tres sencillos pasos:
La funcionalidad de migración multi-esquema está completamente implementada en la CLI de Atlas y requiere iniciar sesión para usarla:
atlas login
Instalar Atlas
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Para instalar la última versión de Atlas, simplemente ejecuta uno de los siguientes comandos en tu terminal, o visita el sitio web de Atlas:
- 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.
Iniciar sesión en Atlas
$ atlas login a8m
You are now connected to "a8m" on Atlas Cloud.
Anotar tus esquemas Ent
El paquete entsql permite anotar un esquema Ent con un nombre de esquema de base de datos. Por ejemplo:
// Annotations of the User.
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db3"),
}
}
Para compartir la misma configuración de esquema entre múltiples esquemas Ent, puedes usar ent.Mixin o definir e incrustar un esquema base:
- Mixin schema
- Base schema
// 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 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 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 holds the edge schema definition of the User entity.
type User struct {
base
}
Generar migraciones
Para generar una migración, usa el comando atlas migrate diff. Por ejemplo:
- 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"
Por defecto, el comando migrate diff genera una lista de sentencias SQL sin indentación. Si prefieres
generar las sentencias SQL con indentación, usa el flag --format. Por ejemplo:
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://postgres/15/dev" \
--format "{{ sql . \" \" }}"
Control del cliente Ent
Cuando se activa la bandera de característica sql/schemaconfig, Ent utiliza automáticamente los nombres de esquema definidos en tu ent/schema como configuración predeterminada en tiempo de ejecución.
Esto significa que cualquier anotación entsql.Schema("db_name") se aplica por defecto, y puedes sobrescribirla opcionalmente en tiempo de ejecución si es necesario.
Para activar esta característica en tu proyecto, usa el flag --feature:
--feature sql/schemaconfig
Una vez activada, también puedes sobrescribir la configuración del esquema en tiempo de ejecución usando la opción ent.AlternateSchema:
c, err := ent.Open(dialect, conn, ent.AlternateSchema(ent.SchemaConfig{
User: "usersdb",
Car: "carsdb",
}))
c.User.Query().All(ctx) // SELECT * FROM `usersdb`.`users`
c.Car.Query().All(ctx) // SELECT * FROM `carsdb`.`cars`