Skip to content

A Database Schema migration auto generator for Golang. Based on gorm

License

Notifications You must be signed in to change notification settings

alob-mtc/migrator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

43 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Migrator

Migrator is a database migration tool, that automates schema migration.

It scans Schema/Model changes and generate SQL migration scripts automatically to reconcile those changes with the Database.

Table of Contents

Features

  • Supports MySQL, PostgreSQL, SQLite, SQL Server.
  • Uses plain SQL for writing schema migrations.
  • Migrations are timestamp-versioned, to avoid version number conflicts with multiple developers.
  • Migrations are run atomically inside a transaction.
  • Supports creating and dropping databases (handy in development/test).
  • Easily plugable to your existing workflows that uses GORM.

Installation

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

  1. You first need Go installed, then you can use the below Go command to install Migrator.
go get -u github.com/alob-mtc/migrator
  1. Import it in your code:
import "github.com/alob-mtc/migrator"

Usage

Register Model

package main

import (
	"fmt"
	migrator "github.com/alob-mtc/migrator/lib"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"time"
)

type User struct {
	ID        string `gorm:"primaryKey;"`
	Username  string `gorm:"index; not null"`
	Active    *bool  `gorm:"index; not null; default:false"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
}

type Product struct {
	ID        string `gorm:"primaryKey;"`
	Name      string `gorm:"index; not null"`
	CreatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
}


func main() {
	// Connecting to postgres
	dns := "postgres://test:test@localhost:54312/test_db"
	db, err := gorm.Open(postgres.Open(dns), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}

	// Register Model
	newMigrator := migrator.New(db, "migrations/sql/")
	newMigrator.RegisterModel(&User{}, &Product{})

}

Creating Migrations

//.....

func main() {

	//.....

	err = newMigrator.Run(db, "create", "add_username_column")
	if err != nil {
		log.Fatal(err)
	}

}

Running Migrations

//.....

func main() {

	//.....

	err = newMigrator.Run(db, "up")
	if err != nil {
		log.Fatal(err)
	}

}

Rolling Back Migrations

//.....

func main() {

	//.....

	err = newMigrator.Run(db, "down")
	if err != nil {
		log.Fatal(err)
	}

}

Internals

TODO:

Contributing

Migrator is written in Go, pull requests are welcome.

About

A Database Schema migration auto generator for Golang. Based on gorm

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages