name: Migrations
sort: 10
Migrations
Models migrations can be generated by using the bee command line tool.
bee generate migration create_user_table -driver mysql
Then new migration file will be generated in database/migrations folder.
package mainimport ("github.com/beego/beego/v2/client/orm/migration")// DO NOT MODIFYtype CreateUserTable_20230928_103629 struct {migration.Migration}// DO NOT MODIFYfunc init() {m := &CreateUserTable_20230928_103629{}m.Created = "20230928_103629"migration.Register("CreateUserTable_20230928_103629", m)}// Run the migrationsfunc (m *CreateUserTable_20230928_103629) Up() {// use m.SQL("CREATE TABLE ...") to make schema update}// Reverse the migrationsfunc (m *CreateUserTable_20230928_103629) Down() {// use m.SQL("DROP TABLE ...") to reverse schema update}
Feel Up() and Down() functions with the next SQL statements.
// Run the migrationsfunc (m *CreateUserTable_20230928_103629) Up() {+ m.SQL("CREATE TABLE users(id int NOT NULL, name varchar(100) NULL, PRIMARY KEY(id));");}// Reverse the migrationsfunc (m *CreateUserTable_20230928_103629) Down() {+ m.SQL("DROP TABLE users")}`
Then run the migration, using the bee command line tool.
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.
describe users;+-------+--------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+--------------+------+-----+---------+-------+| id | int | NO | PRI | <null> | || name | varchar(100) | YES | | <null> | |+-------+--------------+------+-----+---------+-------+
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:
atlas migrate diff --env beego
To learn how to use Atlas with Beego, check out the official documentation.
