Beego Database Migration
Using Git Bash first install driver for Go's database/sql package. Run below two commands one-by-one and install both MySQL and Postgresql driver's
- 1. go get github.com/lib/pq
- 2. go get -u github.com/go-sql-driver/mysql
Creating Goblog Database
- 1. Open PHPMyAdmin/SQLyog or what ever MySQL database management tool that you are using.
- 2. Create a new database "goblog"
Note: Be ready with your database username and password; make sure it must match with the ones on your system.
When you create a migration file, Beego stores it in [/database/migrations] directory. First you need to create database and then migrations folder accordingly inside the beego setup.
Open the command prompt or terminal depending on your operating system For this tutorial, we are using windows.
cd C:\Goweb\src\blog
bee migrate -driver=mysql -conn="root:root@tcp(127.0.0.1:3306)/goblog"
You will get the following message
Now check your database you will get new table "migrations"
bee generate migration user_table
You will get the following message
Now you can examine the contents of the created migration file Open the file
Now that we have successfully updated the migration file, we will add the table definition fields in the migration.
Modify the contents of /database/migrations/20171125_182446_user_table.go
Example
package main
import (
"github.com/astaxie/beego/migration"
)
// DO NOT MODIFY
type UserTable_20171125_182446 struct {
migration.Migration
}
// DO NOT MODIFY
func init() {
m := &UserTable_20171125_182446{}
m.Created = "20171125_182446"
migration.Register("UserTable_20171125_182446", m)
}
// Run the migrations
func (m *UserTable_20171125_182446) Up() {
m.SQL("CREATE TABLE user(id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255), password VARCHAR(255), email VARCHAR(255))")
}
// Reverse the migrations
func (m *UserTable_20171125_182446) Down() {
m.SQL("DROP TABLE user")
}
- func up() defines the function that is executed when the migration is run
- func down() defines the function that is executed when you run migration rollback
bee migrate -driver=mysql -conn="root:root@tcp(127.0.0.1:3306)/goblog"
You will get the following message
Now again check your database you will get new table "user"