DEV Community

Discussion on: How to write & run database migration in Golang

Collapse
 
sergeypodgornyy profile image
Sergey Podgornyy

You can also try using migrator package to write migrations using Go

GitHub logo larapulse / migrator

MySQL database migrator

MySQL database migrator

Build Status Software License codecov Go Report Card GoDoc Mentioned in Awesome Go Release TODOs

MySQL database migrator designed to run migrations to your features and manage database schema update with intuitive go code. It is compatible with the latest MySQL v8.

Installation

To install migrator package, you need to install Go and set your Go workspace first.

  1. The first need Go installed (version 1.13+ is required), then you can use the below Go command to install migrator.
$ go get -u github.com/larapulse/migrator
Enter fullscreen mode Exit fullscreen mode
  1. Import it in your code:
import "github.com/larapulse/migrator"
Enter fullscreen mode Exit fullscreen mode

Quick start

Initialize migrator with migration entries:

var migrations = []migrator.Migration{
    {
        Name: "19700101_0001_create_posts_table"
        Up: func() migrator.Schema {
            var s migrator.Schema
            posts := migrator.Table{Name: "posts"}

            posts.UniqueID("id")
            posts.Varchar("title", 64)
            posts.Text("content", false)
            posts.Timestamps()

            s.CreateTable(posts
Enter fullscreen mode Exit fullscreen mode
Collapse
 
techschoolguru profile image
TECH SCHOOL

Thanks for sharing, Sergey!