Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do database migration with Beego framework?

I need to add a new field to existing table, what is the correct process to do this with Beego?

I am familiar with Django's south: first you generate the migration script with manage.py schema_migration, then execute the migration script manage.py migrate.

Beego has a command bee generate migration to generate migration script in database/migrations/xxx.go. But I don't understand how to use this generated script, it doesn't seem to be connected with anything.

And I don't see any documentation mentioning migration.

like image 508
NeoWang Avatar asked Mar 17 '23 02:03

NeoWang


1 Answers

Came across the same issue, I'm using MySql. Here is how I've done it-

Created a migration file using bee generate:

$ bee generate migration user
2016/06/26 13:36:31 [INFO] Using 'user' as migration name
2016/06/26 13:36:32 [INFO] Migration file generated: /path/to/project/database/migrations/20160626_140247_user.go
2016/06/26 13:36:32 [SUCC] generate successfully created!

Now the file will be generated and below is the content of the file:

package main

import (
    "github.com/astaxie/beego/migration"
)

// DO NOT MODIFY
type User_20160626_140247 struct {
    migration.Migration
}

// DO NOT MODIFY
func init() {
    m := &User_20160626_140247{}
    m.Created = "20160626_140247"
    migration.Register("User_20160626_140247", m)
}

// Run the migrations
func (m *User_20160626_140247) Up() {
    // use m.SQL("CREATE TABLE ...") to make schema update

}

// Reverse the migrations
func (m *User_20160626_140247) Down() {
    // use m.SQL("DROP TABLE ...") to reverse schema update

}

Updated the Up and Down methods. In comment of these methods you can see m.SQL can be invoked to run raw SQL queries. Here you can use alter commands to update the structure.

Once you are done with the changes, you can run bee migrate to apply these migration. Below is the example-

$bee migrate -conn="username:password@tcp(127.0.0.1:3306)/mydb"

Hope this helps.

like image 128
ritesh Avatar answered Apr 02 '23 17:04

ritesh