Driver for Database Package

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.

Migration Command

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.beego migrations directory

Open the command prompt or terminal depending on your operating system For this tutorial, we are using windows.

1. Run the following command to browse to the command prompt.

cd C:\Goweb\src\blog

2. Run the following bee command to create a migration table in Goblog database.

bee migrate -driver=mysql -conn="root:root@tcp(127.0.0.1:3306)/goblog"
Note: host:"127.0.0.1"; username:"root"; password:"root"; port:"3306"; database:"goblog"

You will get the following message
beego migrations

Now check your database you will get new table "migrations"
beego migrations directory

3. Run the following command to create a migration file

bee generate migration user_table

You will get the following message
beego migrations

Now you can examine the contents of the created migration file Open the file
beego migrations

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

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

4. Run the following command to migrate updated migration files

bee migrate -driver=mysql -conn="root:root@tcp(127.0.0.1:3306)/goblog"

You will get the following message
beego migrations

Now again check your database you will get new table "user"
beego migrations directory