name: Migrations

sort: 10

Migrations

Models migrations can be generated by using the bee command line tool.

  1. bee generate migration create_user_table -driver mysql

Then new migration file will be generated in database/migrations folder.

  1. package main
  2. import (
  3. "github.com/beego/beego/v2/client/orm/migration"
  4. )
  5. // DO NOT MODIFY
  6. type CreateUserTable_20230928_103629 struct {
  7. migration.Migration
  8. }
  9. // DO NOT MODIFY
  10. func init() {
  11. m := &CreateUserTable_20230928_103629{}
  12. m.Created = "20230928_103629"
  13. migration.Register("CreateUserTable_20230928_103629", m)
  14. }
  15. // Run the migrations
  16. func (m *CreateUserTable_20230928_103629) Up() {
  17. // use m.SQL("CREATE TABLE ...") to make schema update
  18. }
  19. // Reverse the migrations
  20. func (m *CreateUserTable_20230928_103629) Down() {
  21. // use m.SQL("DROP TABLE ...") to reverse schema update
  22. }

Feel Up() and Down() functions with the next SQL statements.

  1. // Run the migrations
  2. func (m *CreateUserTable_20230928_103629) Up() {
  3. + m.SQL("CREATE TABLE users(id int NOT NULL, name varchar(100) NULL, PRIMARY KEY(id));");
  4. }
  5. // Reverse the migrations
  6. func (m *CreateUserTable_20230928_103629) Down() {
  7. + m.SQL("DROP TABLE users")
  8. }
  9. `

Then run the migration, using the bee command line tool.

  1. bee migrate -driver=mysql -conn="root:pass@tcp(127.0.0.1:3306)/test" -dir="database/migrations"

users table will be created in test database.

  1. describe users;
  2. +-------+--------------+------+-----+---------+-------+
  3. | Field | Type | Null | Key | Default | Extra |
  4. +-------+--------------+------+-----+---------+-------+
  5. | id | int | NO | PRI | <null> | |
  6. | name | varchar(100) | YES | | <null> | |
  7. +-------+--------------+------+-----+---------+-------+

Atlas Integration

Atlas is an open-source database migration tool that has an official integration with Beego.

While Beego’s migrations feature works in most cases, the problem with creating migrations is that the Up() and Down() functions need to be filled with raw SQL statements, written by hand, which is error-prone and time consuming.

Atlas can automatically plan database schema migrations for developers using the official Beego Provider.

After configuring the provider you can automatically plan migrations by running:

  1. atlas migrate diff --env beego

To learn how to use Atlas with Beego, check out the official documentation.